Wednesday, April 13, 2011

Javascript accordion (collapsible menu)


Hi,

In this post, I have created a custom accordion in simple javascript, with a little help from jQuery. But this is not a plugin, so it wont take up too much time to load in the browser. You can download the full source code here. Before going to the explanation, lets first see how it looks like:



The HTML structure that is there, I have done it completely using <ul> and <li>, this would make it easier to customize. Here is a sample HTML of the above:

<ul class="acc_options_ul">
<li class="acc_options"><h1 class="acc_options_title">Option 1</h1>  
<ul class="acc_op_content_ul">  
<li class="acc_op_content">  
content of the section.....  
</li>  
</ul>  
</li>
</ul>

The convention that needs to be followed is, the title of the each section of the accordion must be kept inside an <h1> inside the  <li class="acc_options"> tags. Each <li class="acc_options"> represents each section. You just need to include the style.css and accordion.js in your page and let the JS take care of the rest.

Explanation:


The functionality of the JS file is very simple. First when the page loads I am opening the first section of the accordion by default by the following:
// hiding all the contents
jQuery('.acc_op_content_ul').hide();
// showing the first content by default 
jQuery('.acc_options_ul .acc_op_content_ul:first').slideDown();

//  Changing the class of the section title to make it look as if its selected
jQuery('.acc_options_title:first').toggleClass("acc_options_title_expanded");  

Now in the click event of any section header, I first check whether the section is in collapsed state or not. If yes then all sections are collapsed and the clicked section is expanded by the following code:

if(jQuery(this).next().css("display")!="block"){
jQuery('.acc_op_content_ul').slideUp(200);
jQuery(this).next().slideDown(200);
}

Next I am changing all the section title class to default by:

jQuery(".acc_options h1").removeClass();
jQuery(".acc_options h1").addClass("acc_options_title");

and then assigning the expanded class type to the selected section header by:

jQuery(this).removeClass();
jQuery(this).addClass("acc_options_title_expanded");

This class toggling of the section header is important, as you may want to add a background image to that denoting the expanded or collapsed state.

Download: accordion.zip

Contact me at phpdrops@gmail.com for more customization or queries.

Cheers!!

2 comments:

  1. so...um...where do these files go in the page? (sorry newbie)

    ReplyDelete
  2. Download the sample html from http://php-drops.googlecode.com/files/accordion.zip

    Hope this helps.

    ReplyDelete