How to expand collapse (toggle) div layer using jQuery

Thanks to http://designgala.com/how-to-expand-collapse-toggle-div-layer-using-jquery

In almost all of my projects, I have been using jQuery to toggle the layer. So, I thought of sharing how easy it is to expand div layer and collapse panel using jQuery. When user clicks on the header, the content gets displayed by sliding down and when you again click on the header, the content collapses.

Step 1: Include jQuery Library in head section of your html file.

Step 2:

Come up with your own html elements in body section. I chose div ‘layer1′ to be the main container where collapsible/expandable content would reside.

Next, class ‘heading’ is given to header while div ‘content’ holds the show hide layer for that heading


Header-1


Lorem ipsum dolor sit amet, consectetuer adipiscing elit orem ipsum dolor sit amet, consectetuer adipiscing elit

Header-2


Lorem ipsum dolor sit amet, consectetuer adipiscing elit orem ipsum dolor sit amet, consectetuer adipiscing elit

Header-3


Lorem ipsum dolor sit amet, consectetuer adipiscing elit orem ipsum dolor sit amet, consectetuer adipiscing elit

Step 3:

CSS: Now it totally depends on you to write css for your heading, div. Here’s my version of CSS for this example.

.layer1 {
margin: 0;
padding: 0;
width: 500px;
}

.heading {
margin: 1px;
color: #fff;
padding: 3px 10px;
cursor: pointer;
position: relative;
background-color:#c30;
}
.content {
padding: 5px 10px;
background-color:#fafafa;
}
p { padding: 5px 0; }

Step 4:

Again lets go to head section to add few more javascript codes.


jQuery(document).ready(function() {
jQuery(".content").hide();
//toggle the componenet with class msg_body
jQuery(".heading").click(function()
{
jQuery(this).next(".content").slideToggle(500);
});
});

Thats it!! Expandible-Collapsible panel is ready.

What? You want to see a demo…….This post is the demo in itself 🙂

Caution: When using this in blogger

Because the blogger already has a div with class content which is the parent of all the divs in the page. Hence You need to rename the content class to some other suitable name, before you try to use it with blogger.

0 Replies to “How to expand collapse (toggle) div layer using jQuery”

  1. Excellent script. Thanks.
    Is it possible to place a 'close' button at the foot of the open section?
    Also, is it possible to have an auto-close when opening a new slider?

Leave a Reply