Jquery Tabs Tutorial: The Visual Layout
Jquery Tabs Tutorial: The Visual Layout
In this demo well be creating a simple tabbed interface using html and css and utilising the power of JQuery to control the appearance of the content. The mechanics of this tutorial are to have a tabbed interface that when a link is clicked displays the corresponding information in the content area below. The interface will degrade gracefully if the user has javascript disabled. Demo View demo
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 <li><a href="#tab-2">Tab <li><a href="#tab-3">Tab <li><a href="#tab-4">Tab </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.
$('#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>