Javascript Accordion

| No Comments | No TrackBacks
One feature that is likely to be on a website is an "accordion". An accordion is a styled list of data that can be minimised and maximised based on a mouse click, and these are often used in navigation menus where the menu items can be expanded. I have had to program these fairly recently.

This tutorial will describe how to achieve the accordion effect using Javascript and then show how it could be achieved using the JQuery library.

Note that I have made the initial default option for each accordion panel to display; it is important to ensure that the user is able to see the content in case Javascript is disabled.

The HTML for the accordion will be displayed similar to the format below.

<div class="accordion">
<div class="apanel">
<h1>Header</h1>
<p>Text</p>
</div>
</div>

First, we want to get each 'apanel' and apply a new style via class name ('unselected') to hide all panels except for the first one. internet Explorer does not recognise the Javascript getElementsByClassName() method, so we need to improvise. To make Internet Explorer behave, we first need to loop through all of the DIV elements on the page, then use DIV.className to determine the name of the class. Internet Explorer also cannot handle changing styles in the same manner that other browsers can, so we use the element.style.setAttribute() and element.setAttribute() methods on the element on the element's style to set class names.

if (document.getElementsByClassName) {
    for (var i = 0; i < document.getElementsByClassName("apanel").length; i++) {
        var item = document.getElementsByClassName("apanel")[i];
        if (i == 0) {
            item.style.height='';
        } else {
            item.style.height='20px';
            item.className="apanel unselected";
        }
    }
} else {
    i=0;
    div = document.getElementsByTagName("div");
    while (element = div[i++]) {
        if (element.className == "apanel") {
            if (i == 0) {
                element.style.setAttribute("height","");
            } else {
                element.style.setAttribute("height","20px");
                element.setAttribute("class","apanel unselected");
            }
        }
    }
}

The above will work if you are using the accordion only once on a page. If you have multiple accordions, you should give each accordion an ID; you can then put the above code into a method and pass an ID parameter. The ID parameter can then be referenced to hide/expand all accordion panels except the first one in each group. (See the example below.)

function chooseAccordion(id) {
 // ... place the above code here...
}

The accordion can be styled to however you wish it to look using CSS. I have set the H1 component to have a 'cursor:pointer' and have ensured that all default states have visible content. Only the '.apanel .unselected p' class should be hidden.

Using jQuery is much easier and it uses a lot less code. To achieve the same as above, simply look at the following example.

In jQuery, simply call the addClass() method to append a new class. Use the css() method to add CSS styling, and use the each() method to loop through all elements to pick out the 'apanel' element. The next bit of code captures the onClick event and determines if the tab is already opened or closed and completes the next bit of action, such as opening the clicked-on tab and ensuring that all other tabs are closed.

   jQuery('.apanel').addClass("unselected");
   jQuery('.apanel').css("height", "20px");

   jQuery('.accordion').each(function() {
      panel = jQuery(this).find('.apanel');
      panel.first().removeClass("unselected");
      panel.first().css("height", "");
   });
  
   jQuery('.apanel').click(function() {
      if (jQuery(this).hasClass("unselected")) {
         jQuery('.apanel').addClass("unselected");
         jQuery('.apanel').css("height", "20px");
         jQuery(this).removeClass("unselected");
         jQuery(this).css("height", "");
      } else if (jQuery(this).hasClass("unselected") == false) {
         jQuery(this).addClass("unselected");
         jQuery(this).css("height", "20px");
      }
   });

Animation can also be used with Javascript to create various effects, such as sliding effects when the user clicks onto the accordion.

No TrackBacks

TrackBack URL: http://jenikya.com/cgi-bin/mt5/mt-tb.cgi/351

Leave a comment

Archives

OpenID accepted here Learn more about OpenID