How To Toggle Accordion Box Using jQuery

There are many good tutorials available for expand collapse panel using jQuery. But this one can not only expand collapse but also can change the image using jQuery manipulating CSS.

Step 1: jQuery Library 
First you need to include jQuery Library in head tag 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: HTML
Then we need to build a box with HTML which you want to expand/collapse. So i made "container" div in body and set up a class called "title" and "content" for toggling.

<div class="container">
<p class="title">Title 1 </p>
<div class="content">Lorem ipsum dolor sit amet, consectetuer adipiscing elit orem ipsum dolor sit amet, consectetuer adipiscing elit</div>

<p class="title">Title 2</p>
<div class="content">Lorem ipsum dolor sit amet, consectetuer adipiscing elit orem ipsum dolor sit amet, consectetuer adipiscing elit</div>

<p class="title">Title 3</p>
<div class="content">Lorem ipsum dolor sit amet, consectetuer adipiscing elit orem ipsum dolor sit amet, consectetuer adipiscing elit</div>
</div>


Step 3: CSS
This part is to show the accordion look pretty and usable. In this step, you need two images to toggle. Let's look at how this code works: 

<style>
p {
padding: 5px 0;
color: #fff;
}

.container {
margin: 0 auto;
width: 600px;
}

.title {
background: #000 url(images/icon_arrow_right.jpg) left center no-repeat; /*this is first image to show in title*/
color: #fff;
cursor: pointer;
margin: 1px;
padding-left: 30px;
position: relative;
}

.content {
padding: 0px 10px;
}

/*this class is for when we click title to change second image*/
.title_img {
background:#000 url(images/icon_arrow_down.jpg) left center no-repeat;
padding-left:30px;
}
</style>


Step 4: jQuery Script
Now let's rock with jQuery.
1. hide all content using "hide()" function
2. Add "addClass/removeClass" to toggle title image
3. Using "click()"/ "slideToggle()" function for making all content expand/collapse

<script type="text/javascript">
$(document).ready(function(){
$(".content").hide();
$(".title").toggle(function(){
$(this).addClass("title_img");
}, function () {
$(this).removeClass("title_img");
});
$(".title").click(function(){
$(this).next(".content").slideToggle("fast");
});

});
</script>

 

The demo for Toggle Accordion Box is as shown below. How to toggle accordion box using jQuery

If you want to start your learning experience with jQuery, followings are some links to start your journey.
1) http://www.w3schools.com/jquery/default.asp
2) http://tuljo.com/web-development/expanding-collapsing-sliding-div-jquery

Cheers!

Comments

Great! Thanks for your sharing :)

Add new comment

Similar Articles

Featured Articles