jQuery Tutorial Part 3

Accordion
Here is a sample of accordion. (view demo)



The first line will add a CSS class “active” to the first<h3>element within the<div>(the “active” class will shift the background position of the arrow icon). The second line will hide all theelement that is not the first within the<div>.
When the<h3>element is clicked, it will slideToggle the nextand slideUp all its siblings, then toggle the.

$(document).ready(function(){
$(".accordion h3:first").addClass("active");
$(".accordion p:not(:first)").hide();
$(".accordion h3").click(function(){
$(this).next("p").slideToggle("slow")
.siblings("p:visible").slideUp("slow");
$(this).toggleClass("active");
$(this).siblings("h3").removeClass("active");
});
});

Accordion #2
This example is very similar to accordion#1, but it will let you specify which panel to open as default. (view demo)

In the CSS stylesheet, set .accordion p to display:none. Now suppose you want to open the third panel as default. You can write as $(“.accordion2 p”).eq(2).show(); (eq = equal). Note that the indexing starts at zero.

$(document).ready(function(){
$(".accordion2 h3").eq(2).addClass("active");
$(".accordion2 p").eq(2).show();
$(".accordion2 h3").click(function(){
$(this).next("p").slideToggle("slow")
.siblings("p:visible").slideUp("slow");
$(this).toggleClass("active");
$(this).siblings("h3").removeClass("active");
});
});

Thanks

Leave a Reply