Skip to content

Instantly share code, notes, and snippets.

@gustinmi
Created January 23, 2015 21:31
Show Gist options
  • Save gustinmi/280ef29a18580eee7e4f to your computer and use it in GitHub Desktop.
Save gustinmi/280ef29a18580eee7e4f to your computer and use it in GitHub Desktop.
Javascript tab panel using pure javascript
<!DOCTYPE html>
<html>
<head>
<title>tabs demo</title>
<style type="text/css">
.tabs ul {
list-style-type: none;
margin: 0 2em;
padding: 0;
cursor: pointer;
}
.tabs ul li {
display: inline-block;
padding: 5px;
border: 4px solid #4F1F09;
background-color: #4F1F09;
font-weight: bold;
text-transform: uppercase;
color: #ffffff;
}
.content {
background-color: #B98635;
padding: 1em;
margin-top: -4px; /* the border width of the tabs */
border-top: 4px solid #4F1F09;
}
div.tabpanel .content .tab {
display: none;
}
div.tabpanel.tab1 .content .tab1 {
display: block;
}
div.tabpanel.tab1 .tabs li.tab1 {
background-color: #B98635 ;
border-bottom-color: #B98635;
color: #4F1F09;
}
div.tabpanel.tab2 .content .tab2 {
display: block;
}
div.tabpanel.tab2 .tabs li.tab2 {
background-color: #B98635 ;
border-bottom-color: #B98635;
color: #4F1F09;
}
div.tabpanel.tab3 .content .tab3 {
display: block;
}
div.tabpanel.tab3 .tabs li.tab3 {
background-color: #B98635 ;
border-bottom-color: #B98635;
color: #4F1F09;
}
</style>
</head>
<body>
<div class="tabpanel tab1">
<div class="tabs">
<ul>
<li class="tab1">Tab1</li>
<li class="tab2">Tab2</li>
</ul>
</div>
<div class="content">
<div class="tab tab1">
tab 1
</div>
<div class="tab tab2">
tab 2
</div>
</div>
</div>
<script type="text/javascript">
// get all the tab panels
var panels = document.querySelectorAll("div.tabpanel"), pnl, len = panels.length - 1;
/*jshint -W083 */
for (var i = len; i >= 0; i--) {
pnl = panels[i];
//add click event to list container
pnl.addEventListener("click", function(e){
if(e.target && e.target.nodeName == "LI") {
//replace active tab
this.className = this.className.replace( /(?:^|\s)tab[0-9]{1,}(?!\S)/g , " " + e.target.className );
}
});
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment