Use jQuery SlideToggle to Show/Hide Multiple Rows or Divs

In this tutorial a set of links control the visibility of a number of corresponding divs or rows. It uses jQuery's slideUp and slideToggle sliding effects.

I have used a list as the triggers that will open close the corresponding div/row - clicking a different list item will close the open content and open the relevant one.

This is the HTML markup...

<!-- The links -->
<ul>
<li class="show1 show">Blue Row</li>
<li class="show2 show">Red Row</li>
<li class="show3 show">Green Row</li>
<li class="show4 show">Yellow Row</li>
</ul>



<!-- The Rows -->
<div class="row1 row">Blue Content</div>
<div class="row2 row">Red Content</div>
<div class="row3 row">Green Content</div>
<div class="row4 row">Yellow Content</div>

Each link - which is a button in this case share a common CSS class and a unique class.
Each row also has a unique and common class.

Little bit of CSS

.row {
    display: none;
}

div/content rows initially start hidden.

 

This is the jQuery

jQuery(document).ready(function($){


    $( ".show1" ).click(function(e) {
        e.preventDefault();
            $(".row").not(".row1").slideUp();
            $( ".row1" ).slideToggle( "slow", function() {
    	});
     });
     
    $( ".show2" ).click(function(e) {
        e.preventDefault();
            $(".row").not(".row2").slideUp();
            $( ".row2" ).slideToggle( "slow", function() {
    	});
    });
    
    $( ".show3" ).click(function(e) {
        e.preventDefault();
            $(".row").not(".row3").slideUp();
            $( ".row3" ).slideToggle( "slow", function() {
    	});
     });

    $( ".show4" ).click(function(e) {
        e.preventDefault();
            $(".row").not(".row4").slideUp();
            $( ".row4" ).slideToggle( "slow", function() {
    	});
    });

});

So the jQuery targets each show1 - show4 element, it prevents the default click functionality in html - each element has the same logic applied, so for example in show1 any rows apart from row1 are slid up and hidden with slideUP effect and then only row1 will toggle with slideToggle each time show1 is clicked.

Also a slow animation is used change this to suit and add any further functionality required - demo below.

DEMO

  • Blue Row
  • Red Row
  • Green Row
  • Yellow Row
Blue Content
Red Content
Green Content
Yellow Content

Leave a Comment





%d bloggers like this: