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.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

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

Like this:

<div>
<p>Header-1 </p>
<div>Lorem ipsum dolor sit amet, consectetuer adipiscing elit orem ipsum dolor sit amet, consectetuer adipiscing elit</div>
<p>Header-2</p>
<div>Lorem ipsum dolor sit amet, consectetuer adipiscing elit orem ipsum dolor sit amet, consectetuer adipiscing elit</div>
<p>Header-3</p>
<div>Lorem ipsum dolor sit amet, consectetuer adipiscing elit orem ipsum dolor sit amet, consectetuer adipiscing elit</div>
</div>

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.

<script type="text/javascript">
jQuery(document).ready(function() {
  jQuery(".content").hide();
  //toggle the componenet with class msg_body
  jQuery(".heading").click(function()
  {
    jQuery(this).next(".content").slideToggle(500);
  });
});
</script>

Thats it!! Expandible-Collapsible panel is ready. You may like to view a DEMO.

Author:    Anish Blon

Leave a Reply

Your email address will not be published. Required fields are marked *

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image