jQuery: sliding content tabs

We want to create the effect of sliding content tabs. You click on a tab link and the corresponding content slides down and the slides to right into position. To get things smoother, we'll use the Easing plugin to add an additional effect to the animate() method. Let's see the details.

Here's the basic markup:

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

Some CSS rules to provide the basic layout:

#tabs {
	height: 4em;
	margin: 0;
	padding: 0 1em;
	border-bottom: 1px solid #666;
	list-style: none;
}

#tabs li {
	float: left;
	height: 2em;
	margin: 2em 0 0 0;
}

#tabs a {
	float: left;
	height: 100%;
	line-height: 2;
	font-weight: bold;
	color: #666;
	background: #eee;
	border: 1px solid;
	border-bottom: none;
	border-radius: 6px 6px 0 0;
	padding: 0 2em;
	text-decoration: none;
	margin-right: 1em;
}

#content {
	width: 100%;
	position: relative;
}

div.tab {
	line-height: 1.4;
	display: none;
	width: 300px;
	border-radius: 0 0 10px 10px;
	position: absolute;
	top: 0;
}

div.tab p {
	margin: 0;
	padding: 1em;
}

.one {
	background: #ffc;
}
.two {
	background: #ccc;
}
.three {
	background: #f5f5f9;
}
.four {
	background: #fa9;
}

.five {
	background: #eef;
}

The first thing we need to do is to associate each link with its corresponding content tab. This can be achieved by setting a progressive ID on each content tab and an anchor on the link:

$('li', '#tabs').each(function(i) {
  
    var $a = $('a', $(this));
    var id = 'tab-' + (i + 1);
    
    $a.attr('href', '#' + id);
    
    $('div.tab', '#content').eq(i).
    attr('id', id);
  
  
});

When we click on a link, we have to make sure that only one content tab will be visible each time:

$('li', '#tabs').each(function() {
  
    var tab = $(this);
    var $a = $('a', tab);
    var left = tab.position().left;
    var $id = $a.attr('href');
    
    $a.click(function(event) {
    
          
                   
              $('div.tab').not($id).hide();
              $($id).
              slideDown('slow').animate({
                left: left
              }, 'slow', 'easeOutCirc');
          
          
          
         
      event.preventDefault();
    
    });
  
  
});

We've used the anchor set on each link to retrieve the corresponding content tabs. You can see the 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.