DOM Lab - UI Tabs
by iamKrickE
HTML
<div class="tabbed">
<ul>
<li class="active"><a href="#tab1">Tab 1</a>
</li>
<li><a href="#tab2">Tab 2</a>
</li>
<li><a href="#tab3">Tab 3</a>
</li>
</ul>
<div id="tab1">Tab 1</div>
<div id="tab2">Tab 2</div>
<div id="tab3">Tab 3</div>
</div>
CSS
.tabbed ul {
list-style:none;
margin:0;
padding:0;
}
.tabbed ul li {
float:left;
position:relative;
background-color:#fff;
margin-bottom:-1px;
}
.tabbed ul li a {
display:block;
padding:3px 5px;
border:1px solid #ccc;
border-bottom:0;
color:green;
text-decoration:none;
}
.tabbed ul li.active a {
border-bottom:1px solid #fff;
}
.tabbed > div {
border:1px solid #ccc;
clear:both;
padding:10px;
}
.tabbed > div {
display:none;
}
.tabbed > div:first-of-type {
display:block;
}
JavaScript
// Build some basic UI tabs
//
// Desired behavior:
//
// When user clicks a tab
// that tab becomes marked as "active"
// any other active tabs are no longer active
// the related div (by id) is displayed
// any other unrelated divs are hidden
//
// Hint:
// You'll use the "click" event, and delegation is best
$('.tabbed ul li').on('click', function(){
$('ul li').removeClass('active');
$(this).addClass('active');
var tabID = $(this).find('a').attr('href');
$('div div').hide();
$(tabID).show();
});