JQuery: How to target an element with a click when they all use the same CSS class?

I have 3 div elements on my page and each of them has the same CSS class “.shape”

In my JS, I want to target the current click “.shape”, so some extra html will be inserted at the bottom of the “.shape” with the jQuery slideDown transition.

And when you click on ".shape" again, the additional html will be slideUp.

How can I do this easily? What I have:

$(".shape").click(function() {
    var id = $(this).attr("id");
    var selected = id + "-reveal";
});

In my HTML

<div class="shape" id="shape1">Content</div>
<div class="hidden" id="shape1-reveal">Content</div>

<div class="shape" id="shape2">Content</div>
<div class="hidden" id="shape2-reveal">Content</div>

<div class="shape" id="shape3">Content</div>
<div class="hidden" id="shape3-reveal">Content</div>

I also don't know how to add a switch / slide effect.

EDIT: Solution http://codepen.io/vennsoh/pen/rVjeQy

Not sure if the way I wrote my JS is the most elegant approach.

+4
source share
4

, $(this)

$(".shape").click(function() {
    var clickedShape = $(this);
});

$(this), find().

HTML next(), .

, slideUp(), slideDown() slideToggle().

$(".shape").click(function() {
    var revealThing = $(this).next();

    revealThing.slideToggle();
});

http://jsfiddle.net/yopp6L22/1/

+6

, , $(this)... , .

, , /.

css :

.hidden { display:none }
.visible { display:block }

, visible , :

$(".shape").click(function() {
  if($(this).hasClass("visible")) { $(this).removeClass("visible"); }
  else { $(this).addClass("visible"); }
});
0

jQuery, , 'this' , .

, , "shape", ( "" ). , DOM (.. div), .

, javascript, , , event.target event.currentTarget( DOM ). currentTarget 'this'. https://api.jquery.com/event.currentTarget/

, , . , ovverridden, , , event.currentTarget .

$(".shape").click(function(event) {
   var whatGotClicked = event.currentTarget;
   var whatGotClicked = this; //both wor
});

TL; DR , , , , , .

?

$(".shape").click(function() {
    var id = $(this).attr("id");
    var selected = $(id + "-reveal"); //this will give you a jQuery object targeting the selected id of the reveal element
    selected.toggle(); //at this point you decide, jQuery has alot of helper methods, like slideDown() and slideUp or .animate
});

https://api.jquery.com/?s=toggle

0

Here is jquery code that warns id of clicked items

$('.shape').on('click', function(event) {
    alert(event.target.id);
 });
0
source

All Articles