Tabs Made Easy
by Joe Saad
HTML
<div class="tabs fleft mtt fullw">
<!-- tabs -->
<ul class="tabNavigation">
<li><a href="#progOverview" class="selected">Program Overview</a></li>
<li><a href="#redeemED" class="">Redeem Energy Days</a></li>
<li><a href="#scheduleED" class="">Scheduled Energy Days</a></li>
<li><a href="#viewEDHistory" class="">View Energy Days History</a></li>
</ul>
<!-- tab containers -->
<div id="progOverview" style="display: block;">
<p>Lorem ipsum dolor sit amet.</p>
</div>
<div id="redeemED" style="display: none;">
<p>Sed do eiusmod tempor incididunt.</p>
</div>
<div id="scheduleED" style="display: none;">
<p>Ut enim ad minim veniam</p>
</div>
<div id="viewEDHistory" style="display: none;">
<p>Ut enim ad minim veniam</p>
</div>
</div>
CSS
/* tabbed content */
div.tabs { width:95%; margin-top:10px;}
div.tabs > div { min-height:200px;}
ul.tabNavigation {
list-style: none;
margin: 0;
padding: 0;
}
ul.tabNavigation li {
display: inline;
}
ul.tabNavigation li a {
font-size:smaller;
padding: 3px 5px;
background-color: #ccc;
color: #000;
text-decoration: none;
}
ul.tabNavigation li a:hover {
text-decoration: none;
}
ul.tabNavigation li a.selected,
ul.tabNavigation li a:hover {
background-color: #333;
color: #fff;
padding-top: 7px;
}
ul.tabNavigation li a:focus {
outline: 0;
}
div.tabs > div {
padding: 5px;
margin-top: 3px;
border: 1px solid #b0b0b0;
}
div.tabs > div h2 {
margin-top: 0;
}
#first {
background-color: #f00;
}
#second {
background-color: #0f0;
}
#third {
background-color: #00f;
}
JavaScript
$(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;
});
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();
});