jQuery: accordion tutorial

In this tutorial I will show you how to create a neat accordion effect with jQuery. An accordion is made up of two main parts: an accordion trigger and some hidden content. When you click on the trigger (usually an heading), you check whether the content is still hidden or not. If it's visible, you hide it again, otherwise you show it. Meanwhile, you change some styles (usually a background image) on the trigger depending on the visibility of the content. Most developers use a jQuery slideDown()/slideUp() effect on the content area, so we're going to use that too. First of all, let's start with our markup:

<div id="content">

 <div class="accordion">
 
  <h2>Title</h2><!--the accordion trigger-->
  
  <div><!--accordion content here--></div>
   </div>
   <!--more accordions-->
</div>

We need to specify a different background image for our trigger heading to take into account the two different states of the content, that is, visible or hidden:

#content {
 width: 620px;
 overflow: hidden;
 height: 100%;
 margin: 0 auto;
 font-size: 1.2em;
}

div.accordion {
 width: 201px;
 float: left;
 margin-right: 5px;
}

div.accordion h2 {
 width: 201px;
 height: 41px;
 background: url(accordion.png) no-repeat 0 0;
 margin: 0;
 line-height: 41px;
 color: #fff;
 font-size: 1.2em;
 text-indent: 10px;
 cursor: pointer;
}

div.accordion h2.hover {
 background: url(accordion-hover.png) no-repeat 0 0;
}

div.accordion div {
 width: 100%;
 background: #a40;
 color: #fff;
 line-height: 1.3;
 display: none;
 font-size: 1.1em;
}

div.accordion div p {
 margin: 0 auto;
 padding: 5px;
}

As you can see, two different background images have been specified on our heading, the second added through a class. We've also turned the default mouse cursor to a pointer to indicate that our headings are clickable. Now jQuery:

$(function() {

  $('div.accordion', '#content').each(function() {
  
  
    var $accordion = $(this);
    var $title = $accordion.find('h2');
    var $content = $title.next();
    
    $title.click(function() {
  
      if($content.is(':hidden')) {
      
         $content.slideDown();
         $title.addClass('hover');
      
      
      } else {
      
        $content.slideUp();
        $title.removeClass('hover');
      
      
      }
  
    });
  });


});

When a user clicks on a heading, we check whether the accordion content is hidden or not. If so, we show it and we add our CSS class to the heading. On the contrary, if the content area is visible, we hide it and we remove the previously inserted CSS class from the heading. The purpose of the class switch is simple: display a different background image on the heading to indicate whether the content area can be slide up or down. You can see the demo below.

Demo

Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

2 thoughts on “jQuery: accordion tutorial”

Leave a Reply

Note: Only a member of this blog may post a comment.