jQuery: content tab tutorial

Creating content tabs becomes quite easy with jQuery. In fact, all we need is an unordered list where each item contains a different content section, plus a link for activating each content section. First, we need to define our markup, that in this case is as follows:

<ul id="tabs">

 <li>
   <a href="#">...</a>
 
  <div class="content">...</div>
  
    </li>
    
    <!--more tabs-->
</ul>

What we need now is to basically define some CSS rules for hiding our content section on each tab, plus creating a contextual positioning scheme on each list item. Here's the CSS code:

#tabs {
 height: 3em;
 font: 100% "Trebuchet MS", Trebuchets, sans-serif;
 margin: 0;
 padding: 0 1em;
 list-style: none;
 border-bottom: 1px solid #a40;
}

#tabs li {
 padding: 0 1em;
 height: 2em;
 position: relative;
 top: 0.8em;
 background: #a40;
 border-top: 4px solid orange;
 float: left;
 margin-right: 0.5em;
 line-height: 2;
}

#tabs li a {
 color: #fff;
 text-decoration: none;
}

#tabs li div.content {
 display: none;
 position: absolute;
 left: 0;
 background: #ececec;
 width: 400px;
 padding: 1em;
}

#tabs li div.content h2 {
 margin: 0;
 font: normal 1.5em Arial, sans-serif;
 color: #a40;
}

#tabs li div.content p {
 line-height: 1.4;
 margin-top: 5px;
}

Now our content section has been absolutely positioned within its list item which, in turn, has been relatively positioned. Then we can create our jQuery code in the form of a plugin to be attached to each link in the list:

(function($) {

  $.fn.contentTab = function(options) {
  
    var element = this;
  
    var settings = {
    
      wrapper: 'div.content'    
    };
    
    options = $.extend(settings, options);
    
    return this.each(function() {
    
      $(this).click(function(e) {
      
        var current = $(this).parent().find(options.wrapper);
        
        $(this).parent().parent().find(options.wrapper).not(current).hide();
      
        var height = $(this).parent().height();
      
        $(this).parent().find(options.wrapper).
        css('top', height + 1).slideDown(); 
      
        e.preventDefault();
      });
    
    });
  
  };

})(jQuery);

We first check if there are no other content sections visible when a link is activated. If so, we hide them except the current one. Then we set the CSS top property of our content section to the height of the current list item and then we show our content section using slideDown(). A practical example follows:

$(document).ready(function() {

  $('#tabs li a').contentTab();

});

You can see a demo below.

Demo

Live demo

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.