Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: How do I target the clicked element when they all share the same CSS class?

I have 3 div elements on my page and each of them has a same CSS class ".shape"

Within my JS, I want to target the current click ".shape" so that some extra html will get inserted to the bottom of the ".shape" with a jQuery slideDown transition.

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

How do I do that in an easy way? 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 have no idea how to add in the toggle + sliding effect.

EDIT: The solution http://codepen.io/vennsoh/pen/rVjeQy

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

like image 869
Vennsoh Avatar asked Mar 15 '23 21:03

Vennsoh


1 Answers

Target the element clicked with $(this)

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

Once you have $(this), you can target elements inside of it with find().

Or in the case of your HTML, use next() to locate the reveal element after your shape.

Once you have found the proper element, you can slideUp(), slideDown(), or slideToggle().

Example

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

    revealThing.slideToggle();
});

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

like image 90
kspearrin Avatar answered Apr 08 '23 11:04

kspearrin