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>Blue Row</li> <li>Red Row</li> <li>Green Row</li> <li>Yellow Row</li> </ul> <!-- The Rows --> <div>Blue Content</div> <div>Red Content</div> <div>Green Content</div> <div>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
2 comments
Max2505
Would this also be useable with image maps?
I tried, but I’m not getting the div’s to show…
B
This was SUPER helpful.
I had a distance between the buttons I have triggering the script and where the div showed up.
So I added an anchor link.
Blue Row
Blue Content
In order to get it to travel down the page to view the content automatically