05 July, 2010

Accordion style show/hide divs using jQuery

This is just a start, but thought it might be of some help to others, so posted the code snippet. The code uses class for divs and anchor tags. This is a simple demo of accordion like tabs, but i've just done show and hide of divs using jQuery selectors.
When a link above a div is clicked, the div immediately below the anchor tag is displayed and all other divs are hidden.
Some animation can also be used in place of just show hide.If none of other divs are displayed as block then the current div is not closed. And by default first div is displayed when page is loaded.
Check out the following code snippet

$(document).ready(function() {
//display by default the first div content
$(".acc:first").css('display', 'block');
//attach click event to anchor tags
$(".atest").click(function() {
//check for the display block or none of the immediate div next to anchor tag
var displayStatus = $(this).next().css('display');
if(displayStatus == "block") {
var otherDivsStatus = $(".acc").not($(this).next()).css('display');
if(otherDivsStatus == "block") {
$(this).next().hide('slow');
}
}
else {
//hide all the divs except for the current div
$(".acc").not($(this).next()).hide('slow');
$(this).next().show('slow');
}
});
});
/*
Just a test html, this can be changed as needed

First Block

This is first div

Second Block

This is second div

Third Block

This is third div


*/

No comments: