Question

I have four of the ".content" sections on a page.I want to be able to toggle each section but also show ALL of the sections to display all of the ".content". When I tried to you add a show all button, the toggle would stop working. Still getting used to jQuery, any help would be greatly appreciated!

Here's the structure of the HTML:

<div class="row add-top">
         <div class="span4">

         <p class="expand"><a href="#">Show All</a></p>
          <p class="contract"><a href="#">Hide All</a></p>


    <p class="heading"><strong>Week 01 - Welcome!</strong></p><!--  WEEK --> 
    <section class="content">

        <p></p>
    </section>
    </div>  


$(document).ready(function () {
    $(".content").hide();
    //toggle the componenet with class msg_body
    $(".heading").click(function () {
        $(this).next(".content").slideToggle(500);
        $(".content").hide();
        //toggle the componenet with class msg_body
        $(".expand").click(function () {
            $(this).next(".content").slideToggle(500);
            $(".content").hide();
            //toggle the componenet with class msg_body
            $(".contract").click(function () {
                $(this).next(".content").slideToggle(500);
            });
        })
    });
}
Was it helpful?

Solution

Try

$(document).ready(function () {
    var $contents = $(".content").hide();
    $(".heading").click(function () {
        var $next = $(this).next(".content").stop(true, true).slideToggle(500);
        $contents.not($next).hide();
    });
    $(".expand").click(function () {
        $contents.stop(true, true).slideDown()
    })
    $(".contract").click(function () {
        $contents.stop(true, true).slideUp()
    });
})

Demo: Fiddle

OTHER TIPS

You could try like this

jQuery toggle() to hide/show collapse content

Toggle-Jquery

May be it will helpful for you.Thanks.

Try to combine all click events as these all working same and use slideDown() in place of slideToggle(), also don't use next() use $('.content') selector to toggle like,

$(function(){
    $(".content").hide();
    //toggle the componenet with class msg_body
    $(".heading, .expand, .contract").click(function () {
        $(".content").hide().slideDown(500);
    });
});

Demo

And if you have multiple-content then use closest() try this,

$(function(){
    $(".content").hide();
    //toggle the componenet with class msg_body
    $(".heading, .expand, .contract").click(function () {
        $(".content").hide();

        // let row is parent for every div containnig heading, expan, contract
        $(this).closest('.row').find(".content").slideDown(500);
    });
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top