Robin Papa
Robin Papa

Reputation: 180

Toggle div's with the same classes but individually, not all at once?

I've got the following HTML and because I'm using Wordpress, I cannot change the class for each div.

<div class="show_hide">content1</div>
<div class="extended">extension of content 1</div>
<div class="show_hide">content2</div>
<div class="extended">extension of content 2</div>

My jQuery script is as follows:

 <script type="text/javascript">

    $(document).ready(function(){


        $(".sliding").hide(0);
        $(".show_hide").show(0);

    $('.show_hide').click(function(){
    $(".sliding").slideToggle(0);
    });

});

</script>

Now, when clicking on the show_hide div, both div's with class "extended" show. I would like to show only the extension the div clicked on. Can anyone help me with this?

Upvotes: 4

Views: 336

Answers (2)

Aaron Digulla
Aaron Digulla

Reputation: 328614

In callback functions, the variable this will contain a reference to the DOM node that triggered the event:

$(this).next().slideToggle(0);

Upvotes: 3

James Allardice
James Allardice

Reputation: 165971

If the .extended element is the immediately following sibling of the .show_hide element, you can use next:

$('.show_hide').click(function(){
    $(this).next().slideToggle(0);
});

If there are other elements in between, you can use nextAll, and then reduce the selection to the first match (with eq):

$('.show_hide').click(function(){
    $(this).nextAll('.extended').eq(0).slideToggle(0);
});

Upvotes: 7

Related Questions