DOM Lab - UI Tabs

by Satish Kesiboyana

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;
}

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");
console.log(tabContainer);
console.log(tabs);
tabContainer.addEventListener('click', function (e) {
    console.log("Target: " + e.target);
    for( var i=0; i<tabs.length; i++) {
        tabs[i].style.display = "none";
    }
    var matcher =/(#.+)/;
    var matches = matcher.exec(e.target.href);  
    if (matches) {
        tabToShow = document.querySelector(matches[0]);
        console.log(tabToShow);
        tabToShow.style.display = "blocked";
    }
});