The Visual Layout
Firstly we are going to look at our visual layout. For this tutorial I have kept the layout simple with a common tabbed interface with a content area below.
The HTML
Secondly we are going to set up the page structure for our tabbed interface using an unordered list for the navigation controls and a container div for each section. Each link is linked to each section div by the divs corresponding unique id, this is required for our jQuery and we will cover this in the next section.
<div id="tabs">
<ul>
<li><a href="#tab-1">Tab One</a></li>
<li><a href="#tab-2">Tab Two</a></li>
<li><a href="#tab-3">Tab Three</a></li>
<li><a href="#tab-4">Tab Four</a></li>
</ul>
<div id="tab-1">
<h3>Tab 1</h3>
<p>Some content</p>
</div>
<div id="tab-2">
<h3>Tab 2</h3>
<p>Some content</p>
</div>
<div id="tab-3">
<h3>Tab 3</h3>
<p>Some content</p>
</div>
<div id="tab-4">
<h3>Tab 4</h3>
<p>Some content</p>
</div>
</div>
The CSS
#tabs {
font-size: 90%;
margin: 20px 0;
}
#tabs ul {
float: right;
background: #E3FEFA;
width: 600px;
padding-top: 4px;
}
#tabs li {
margin-left: 8px;
list-style: none;
}
* html #tabs li {
display: inline; /* ie6 double float margin bug */
}
#tabs li,
#tabs li a {
float: left;
}
#tabs ul li a {
text-decoration: none;
padding: 8px;
color: #0073BF;
font-weight: bold;
}
#tabs ul li.active {
background: #CEE1EF url(img/nav-right.gif) no-repeat right top;
}
#tabs ul li.active a {
background: url(img/nav-left.gif) no-repeat left top;
color: #333333;
}
#tabs div {
background: #CEE1EF;
clear: both;
padding: 20px;
min-height: 200px;
}
#tabs div h3 {
text-transform: uppercase;
margin-bottom: 10px;
letter-spacing: 1px;
#tabs div p {
line-height: 150%;
}
The JQuery
I have commented each line of the jQuery to explain why each step was undertaken.
<script type="text/javascript">
$(document).ready(function(){
$('#tabs div').hide(); // Hide all divs
$('#tabs div:first').show(); // Show the first div
$('#tabs ul li:first').addClass('active'); // Set the class of the first link to active
$('#tabs ul li a').click(function(){ //When any link is clicked
$('#tabs ul li').removeClass('active'); // Remove active class from all links
$(this).parent().addClass('active'); //Set clicked link class to active
var currentTab = $(this).attr('href'); // Set variable currentTab to value of href attribute of clicked link
$('#tabs div').hide(); // Hide all divs
$(currentTab).show(); // Show div with id equal to variable currentTab
return false;
});
});
</script>