Thursday, November 18, 2010

9:45 PM
In this post, I’ll show you how easy it is to show expandable and collapsible toggle panel using jQuery. When you click on the heading, the content gets displayed by sliding and when you again click on the heading again, it gets collapsed.
Now let’s look at the html code,



<div class="msg_list">
<p class="msg_head">Header-1 </p>
<div class="msg_body">
orem ipsum dolor sit amet, consectetuer adipiscing elit orem ipsum dolor sit amet, consectetuer adipiscing elit
</div>
<p class="msg_head">Header-2</p>
<div class="msg_body">
orem ipsum dolor sit amet, consectetuer adipiscing elit orem ipsum dolor sit amet, consectetuer adipiscing elit
</div>
<p class="msg_head">Header-3</p>
<div class="msg_body">
orem ipsum dolor sit amet, consectetuer adipiscing elit orem ipsum dolor sit amet, consectetuer adipiscing elit
</div>
</div>



As you can see above, the whole message panes contained inside the div with class name “msg_list”. And, the header element where you click is defined with the class “msg_head” and after that there is element with class “msg_body” which contains the message or text which is expandable or collapsible.
Now let’s look at the CSS attributes of these three classes,

p {
padding: 0 0 1em;
}
.msg_list {
margin: 0px;
padding: 0px;
width: 383px;
}
.msg_head {
padding: 5px 10px;
cursor: pointer;
position: relative;
background-color:#FFCCCC;
margin:1px;
}
.msg_body {
padding: 5px 10px 15px;
background-color:#F4F4F8;
}

Now, let’s look at the JavaScript code to make the pane toggling i.e collapsible and expandable,

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
  //hide the all of the element with class msg_body
  $(".msg_body").hide();
  //toggle the componenet with class msg_body
  $(".msg_head").click(function()
  {
    $(this).next(".msg_body").slideToggle(600);
  });
});
</script>

As you can see above, first of all jQuery framework is used. After that, all the element with the class name “msg_body” is collapsed when the page is loaded. And you can see, the “slideToggle()” function of jQuery is used to expand and collapse the “div” with class “msg_body”. When user clicks on the element with the class “.msg_head”, then div with class “msg_body” next to it, gets toggled with sliding effect, making toggle panel using jQuery.

If you want to learn more about jQuery then you can check the following books and buy them.I really recommend the book “jQuery in Action” for starting your way for jQuery.

0 comments: