DOM Lab - UI Tabs
by Ryan Morris
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;
}
.hide{
display:none;
}
.show{
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
var tabContainer = document.querySelector(".tabbed");
var tabs = document.querySelectorAll(".tabbed > div");
tabContainer.addEventListener("click", function(e) {
// set all Tab Pages to hidden
for (var i=0; i<tabs.length; i++) {
tabs[i].style.display = "none";
}
// Deactivate old active Tab Button
var activeLi = document.querySelector("li.active");
if (activeLi) {
activeLi.className = "";
}
// Activate current Tab Button
e.target.parentNode.className = "active";
// Get id of Tab Page to display
var matches = /(#.+)/.exec(e.target.href);
// Display Tag Page
if (matches) {
var tabToShow = document.querySelector(matches[0]);
tabToShow.style.display = "block";
}
});