Creating Content Tabs with jQuery

Posted in jQuery

jQuery Tabs

Organizing content into tabs is a great way to clean up your web page if it contains loads of information. Tabs let you show a piece of information at a time which can be easily digested by the user. User can then click on tabs to view more information. With jQuery, creating tabs is quite simple and quick, here’s how to do it.

Firstly, we need to have content to put under tabs, I’ve created a div name container that’ll contain all the html content for various tabs. To create the top navigation, I’ve used an unordered list of links with their href’s corresponding to id’s of their respective content blocks.

<div id="container">
 <ul id="tabs">
        <li><a href="#tab1">Tab 1</a>
        <li><a href="#tab2">Tab 2</a>
        <li><a href="#tab3">Tab 3</a>
    <div id="tab1"><h2>First</h2>
            <p>Content for tab 1</p>
    <div id="tab2"><h2>Second</h2>
            <p>Content for tab 2</p>
    <div id="tab3"><h2>Third</h2>
            <p>Content for tab 3</p>

Now we need to apply some styles using CSS to make the navigation links horizontal and some styles to control looks of the content. Here’s the CSS code to use.

#container{ width:600px; margin:50px auto; border:1px solid #ccc; background:#fff; padding:5px;} 
#tabs{ list-style:none; margin:3px 0; padding:0; }
#tabs li{ display:inline; margin:0px 1px 0 0; }
#tabs li a{ padding:4px; text-decoration:none; color:#3366cc; border:1px solid #e0e0e0; font-size:11px; font-family:Tahoma; }
#tabs li a:hover{ background:#3399cc; color:#f0f0f0; }
#container div{ border:1px solid #ccc; padding:5px; background:#eee;}
#tabs li a.selected{ background:#eee; color:#333; cursor:default;  }

Now comes the jQuery part. Add the reference to jQuery library in head tag if you haven’t already. Use this jQuery code in the ready function to implement tabs.

		var tabcontainers=$('#container > div');
		//hide every content div
		$('#tabs > li a').click(function(){
			//On click on the tab navigation link
			//show content block corresponding to link clicked
			$('#tabs > li a').removeClass('selected');
			return false;			
		}).filter(':first').click();//click event for first link on pageload

To explain this code, first of all we make all content blocks hidden and when a navigation link is clicked, we check its href and then corresponding to that hash value, the content block is shown.



Subscribe to Full RSS Feed

RSS FeedIf you found this article useful, then consider subscribing to our RSS Feed or e-mail updates to stay updated with latest Web Design/ Development articles. You can also follow @webdevplus on twitter for latest updates.

3 Responses (Add Your Comment)

  1. merlinvicki says:

    Very nice tutorial, but poor UX. Adding a demo would have greatly enhanced the user experience of this very nice tutorial.

Comments are closed for this post.