A simple accordion with jQuery

Creating a simple accordion is not difficult with jQuery. To begin, let's create a markup structure like this:

<div class="accordion">
    <h2>...</h2>
    <p>...</p>
    <h2>...</h2>
    <p>...</p>
    <!-- more similar elements -->
</div>

Then we add some styles:

body {
 margin: 0 auto;
 width: 570px;
 padding: 2em 0;
 font: 76%/120% Arial, Helvetica, sans-serif;
}
.accordion {
 width: 480px;
 border-bottom: 1px solid #c4c4c4;
 font-size: 1.1em;
}
.accordion h2 {
 background: #e9e7e7 url("img/arrow.gif") no-repeat right -51px;
 padding: 7px 15px;
 margin: 0;
 height: 100%;
 font-size: 120%;
 font-weight: bold;
 line-height: 100%;
 border: solid 1px #c4c4c4;
 border-bottom: none;
 cursor: pointer;
}
.accordion h2.hover {
 background-color: #e3e2e2;
}
.accordion h2.active {
 background-position: right 5px;
}
.accordion p {
 background: #f7f7f7;
 margin: 0;
 padding: 10px 15px 20px;
 border-left: solid 1px #c4c4c4;
 border-right: solid 1px #c4c4c4;
 display: none;
}

Two things to note here: first, each h2 element has a background image to create the effect of a clickable item (enforced by the declaration cursor: pointer); then, each paragraph following an heading is initially hidden. With all this in mindi, let's add jQuery:

$(document).ready(function(){
 
 $('.accordion h2').mouseover(function() {
 
     $(this).addClass('hover');
 
 });
 
 $('.accordion h2').mouseout(function() {
 
     $(this).removeClass('hover');
 
 });

 $('.accordion h2').click(function(){
  $(this).next('p').slideToggle('slow')
  .siblings('p:visible').slideUp('slow');
  $(this).toggleClass('active');
  $(this).siblings('h3').removeClass('active');
 });

});

To create the sliding effect, we use the slideUp() and slideToggle() methods. Notice how the background image on each heading changes when an user clicks on the heading (thanks to the .active CSS class, which is first added and then removed). Also notice that we've created an hove effect on heading by means of the .hover class. This is required by Internet Explorer 6 that doesn't support the :hover pseudo-class on elements other than hyperlinks. You can see the final result here.

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

Leave a Reply

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