For this tutorial I have created two screencasts demonstrating how to quickly apply a dash of jQuery to different layouts of markup, which, if the markup is well designed, it will automatically degrade nicely without JavaScript enabled. In a future article we will cover default browser functionality (i.e. supporting back, forward and bookmark buttons) and saving tab states.
Conventional and simple markup
Watch the jQuery tabs screencast – part 1 (flash version)
(QuickTime version is approx. 25Mb, flash version is streaming)
View demo and code used in screencast
Typical tabbing structure, and the one used in the demo is usually marked up as follows:
<div class="tabs">
<!-- tabs -->
<ul class="tabNavigation">
<li><a href="#message">Send a message</a></li>
<li><a href="#shareFile">Share a file</a></li>
<li><a href="#arrange">Arrange a meetup</a></li>
</ul>
<!-- tab containers -->
<div id="message">
<p>Lorem ipsum dolor sit amet.</p>
</div>
<div id="shareFile">
<p>Sed do eiusmod tempor incididunt.</p>
</div>
<div id="arrange">
<p>Ut enim ad minim veniam</p>
</div>
</div>
Here’s the jQuery used, though slightly adapted from this screencast:
$(function () {
var tabContainers = $('div.tabs > div');
$('div.tabs ul.tabNavigation a').click(function () {
tabContainers.hide().filter(this.hash).show();
$('div.tabs ul.tabNavigation a').removeClass('selected');
$(this).addClass('selected');
return false;
}).filter(':first').click();
});
Real World example
Watch the jQuery tabs screencast – part 2 (flash version)
(QuickTime version is approx. 30Mb, flash version is streaming)
View demo and code used in screencast
Chris Mahon requested a tutorial that explained how to apply tabbing to markup that doesn’t follow the above markup convention.
In his case, the tabs were in a different DIV to the tab containers, in addition, one item in the UL wasn’t a tab, but used to link to a different page.
Here’s the jQuery tab code used:
$(function () {
var tabs = [];
var tabContainers = [];
$('ul.tabs a').each(function () {
// note that this only compares the pathname, not the entire url
// which actually may be required for a more terse solution.
if (this.pathname == window.location.pathname) {
tabs.push(this);
tabContainers.push($(this.hash).get(0));
}
});
$(tabs).click(function () {
// hide all tabs
$(tabContainers).hide().filter(this.hash).show();
// set up the selected class
$(tabs).removeClass('selected');
$(this).addClass('selected');
return false;
});
});
Taking it further
These screencasts are really designed to help you understand the thought process and how to go about writing the code for the tabs.
In a future article I will explain how to convert this code to a plugin that can be reused on your projects, and what to watch out for when making the code reusable.
Of course, you can always use the jUI Tabs to accomplish the task if you require more dynamic functionality.
You should follow me on Twitter here I tweet about jQuery amongst the usual tweet-splurges!