3D-kreativ
3D-kreativ

Reputation: 9299

SlideToggle elements with same class and same script

How can I use this in jQuery to be able to click on the + sign to slideToggle the .expand element? I want to make the code simple and use the same script for all articles on the page. One solution would be to use a unique id for each articles element and detect each click for that id, but then I guess the script would be unnecessary big and complicated.

How can I improve my script below to be able to use it for several articles? Perhaps it would be easier/better to use slideDown and slideUp instead of slideToggle?

<article class="post">
    <header>
        <h2>Headline</h2>
    </header>
    <img src="images/test.jpg">
    <div class="expand">Text</div>
    <div class="click">+</div>
</article>

<article class="post">
    <header>
        <h2>Headline</h2>
    </header>
    <img src="images/test.jpg">
    <div class="expand">Text</div>
    <div class="click">+</div>
</article>
$(document).ready(function(){
    $(".expand").hide();
    $(".click").click(function(){ 
        $(".expand").slideToggle();
    });
});

Upvotes: 1

Views: 84

Answers (2)

Kevin Grosgojat
Kevin Grosgojat

Reputation: 1379

This code get the parent element of the clicked element wich has the .click class and find the child element wich has the .expand class.

$("body").on("click", ".click", function(){
     $(this).parent().children(".expand").slideToggle();
});

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

You can use DOM traversal to find the related .expand from the clicked .click element.

You can use the this keyword within the click handler to get a reference to the .click element which raised the event. From there you can use the prev() method to find the required .expand. Try this:

$(".click").click(function(){ 
    $(this).prev('.expand').slideToggle();
});

Working example

Also note that it's better practice to use CSS to set the initial state of the elements in the page.

Upvotes: 1

Related Questions