jQuery horizontal accordion

We want to create an horizontal accordion with jQuery and some nice animation effects to show when we expand our items. We start with a basic markup like this:

<div id="accordion">

    <h2 class="main"><a href="#main-content">Title</a></h2>
    
    <div id="main-content" class="content">
        <p>...</p>
    </div>
    
    <h2 class="sub"><a href="#sub-content">Title</a></h2>
    
    <div id="sub-content" class="content">
        <p>...</p>
    </div>

</div>

Then we add some CSS styles to create the effect of a side panel menu:

#accordion {
 width: 100%;
 height: 100%;
 overflow: hidden;
}

#accordion h2 {
 margin: 0 10px 0 0;
 width: 5px;
 height: 35px;
 display: block;
 float: left;
 background: url(img/expand.gif) no-repeat 0 0;
}

#accordion h2 a {
 float: left;
 display: block;
 height: 35px;
 width: 5px;
 text-indent: -1000em;
 outline-style: none;
               
}

#accordion div.content {
 float: left;
 width: 200px;
 margin: 0;
 padding-right: 10px;
}

#accordion div.content p {
 margin-top: 0;
}

Each panel is made up by an heading and an hyperlink which are left-floated and the heading has a background image. The whole area is clickable because the child link has exactly the same dimensions of its parent. Now let's add jQuery:

$(document).ready(function() {

    $('#accordion .content').hide().css('width', '100px');
    
    $('#accordion h2').each(function() {
    
        var $h2 = $(this);
        
        $h2.find('a').click(function() {
 
 $h2.next().animate({width: '200px'}, 'slow');
 
 return false;
 
        });
    
    
    });
});

After hiding all the panels next to our tabs, we've assigned to them a width that is less than their original CSS width. Why so? Because later in the source we use the animate() method to create our effect: when an user clicks on a tab, he/she will see the text growing until the whole block gains its original dimensions. 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.