jQuery

jQuery Tabs made easy

The other day I needed to create a block (or widget) with tabs, so I started checking different jQuery based tab solutions but they were all very large for what I needed. Most of the jQuery based tabs I found had a lot of functionalities to fulfill everything you need, but they end up being quite large, bloated and complex. I wrote this small jQuery dependant code to create my own tabs widget and thought you could find it useful.

The markup…

…is quite simple

<ul class="htabs hide">
<li>
<h2><a href="#design">Graphic design</a></h2>
</li>
<li>
<h2><a href="#development">Development</a></h2>
</li>
<li>
<h2><a href="#freebies">Freebies</a></h2>
</li>
</ul>
<div class="tabs">
<div id="design" class="tab">
<ul>
<li><a href="#">Typography</a></li>
<li><a href="#" target="_blank">Typefaces</a></li>
<li><a href="#">Painting</a></li>
<li><a href="#">Grid systems</a></li>
<li><a href="#">Optical balance</a></li>
</ul>
</div>
<!-- more tabs --></div>

Style

The CSS is quite large because I added different bullets for you to experiment, so you can get it from the source. It doesn’t have anything that will influence the behaviour. You can remove the CSS and you will get a plain markup for the jQuery tabs that will still work… you don’t believe me?

jQuery

Now, the jQuery code to create our tabs!

jQuery(document).ready(function(){
 //if this is not the first tab, hide it
 jQuery(".tab:not(:first)").hide();
 //to fix u know who
 jQuery(".tab:first").show();
 //when we click one of the tabs
 jQuery(".htabs a").click(function(){
 //get the ID of the element we need to show
 stringref = jQuery(this).attr("href").split('#')[1];
 //hide the tabs that doesn't match the ID
 jQuery('.tab:not(#'+stringref+')').hide();
 //fix
 if (jQuery.browser.msie && jQuery.browser.version.substr(0,3) == "6.0") {
 jQuery('.tab#' + stringref).show();
 }
 else
 //display our tab fading it in
 jQuery('.tab#' + stringref).fadeIn();
 //stay with me
 return false;
 });
});

Leave a Reply

Your email address will not be published.Required fields are marked *