Last time I’ve written an article about how to make expand-collapse toggle panel using jQuery. Now, this time I’ll show you how to make collipsible accordion using jQuery.An accordion is a toggle pane where one pane slides down the other pane slides up.
View Demo
HTML Code :
<div id="firstpane" class="msg_list"> <p class="msg_head">News-Head-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">News-Head-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">News-Head-3</p> <div class="msg_body"> orem ipsum dolor sit amet, consectetuer adipiscing elit orem ipsum dolor sit amet, consectetuer adipiscing elit </div> </div>
Since, I’ve shown two examples, I’ve distinguished two container with two different id “firstpane” and “secondpane”.The html code of above is of first pane, The second pane’s HTML code is same with different id of the container “div”.
CSS Code :
p {
padding: 0 0 1em;
}
.msg_list {
list-style: none;
margin: 0;
padding: 0;
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;
}
the above CSS code is straightforward for making collapsible accordion and you can change the various attribute of the class as your need. But keep in mind that the “position” property of “msg_head” should be “relative”.
Javascript Code:
<script type="text/javascript" src="jquery.js"></script>
First of all, jQuery library is added in our source code. And the following codes are used for displaying the effect of expanding and collapsing.
//hide the all of the element with class msg_body
$(".msg_body").hide();
//slides the element with class "msg_body" when paragraph with class "msg_head" is clicked
$("#firstpane p.msg_head").click(function()
{
$(this).next("div.msg_body").slideToggle(700).siblings("div.msg_body").slideUp("slow");
});
//slides the element with class "msg_body" when mouse is over the paragraph
$("#secondpane p.msg_head").mouseover(function()
{
$(this).next("div.msg_body").slideDown("slow").siblings("div.msg_body").slideUp("slow");
});
As you can in the firt line, all the element with the class “msg_body” is hidden in the document. And after that, when a paragraph with class “msg_head” within id “firstpane” is cliked , the next “div” element with class “msg_body” is slidded toggling. But for the “secondpane”, when mouse is moved over the element with class “msg_head”, the next element with class “msg_body” gets slided down and all the other siblings with class “msg_body” gets slided up creating the effect of collapsible accordion.
Click here to download the full source code
Related posts:
