Simple javascript tabs

We have all seen them, the tabbed views on a web page that split up your content.

Did you know how simple it is ( using jquery ) to create this tabbed box.

First, lets look at the markup:

<div class="tab_set">
    <div class="tab_nav">
        <ul>
            <li id="navtab_details"><a href="javascript:simple_tab('details')">Details</a></li>
            <li id="navtab_reviews"><a href="javascript:simple_tab('reviews')">Reviews</a></li>
        </ul>
    </div>
    <div id="tab_details" class="tab">
        details tab contents
    </div>
    <div id="tab_reviews" class="tab" style="display: none;">
    <div>
        review tab contrents
    </div>
</div>

The markup is importan so that the javascript can manipulate the styles of the right components.

The javascript for the simple_tab function is quite simple ( no pun intended )

 function simple_tab(id) {
    $('#navtab_'+id).siblings('li').removeClass('active');
    $('#navtab_'+id).addClass('active');
    
    $('#tab_'+id).siblings('.tab').hide();
    $('#tab_'+id).show();
}

Make sure that the id you pass in matches the id on the tab itself and the navigation li for that tab. That is all there is too it.

Beyond that, you just need to style your tab_set, here is how I styled mine in the screenshot:

 .tab_set {
    margin: 5px 0;
}

.tab_set .tab_nav {
    border-bottom:1px dotted #000000;
}

.tab_set .tab_nav ul {
    list-style-type:none;
    margin: 0;
    padding: 0;
}

.tab_set .tab_nav ul li {
    border-right:1px dotted #000000;
    float:left;
    margin:0;
    padding:0;
}

.tab_set .tab_nav ul li a {
    display: block;
    margin: 2px;
    padding: 2px 5px;
    text-decoration: none;
}

.tab_set .tab_nav ul li.active a,.tab_set .tab_nav ul li a:hover {
    background: #555555;
    color: #fff;
}

.tab_set .tab {
    border-bottom:1px dotted #000000;
    padding: 4px;
}

Have fun

Comments

05/30/2011 3:35pm
For this to work, you need each of your tabs to have class tab, which isn't shows in the example
05/31/2011 11:53am
thanks for pointing that out, looks like i had copied an old version to the blog post. I have updated it with the class and tested it now.

Leave a comment

To leave a comment, please log in / sign up