Skip to content

Instantly share code, notes, and snippets.

@cossssmin
Forked from Jiert/JavaScript-Tabs.js
Last active May 17, 2018 16:24
Show Gist options
  • Save cossssmin/2462a471d32119998ee6766a05c5122d to your computer and use it in GitHub Desktop.
Save cossssmin/2462a471d32119998ee6766a05c5122d to your computer and use it in GitHub Desktop.
Creating Tabs with Vanilla JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<title>Tabs</title>
<style>
.tabs .active a { color: red; }
.tab-pane:not([aria-expanded="true"]) {display: none;}
</style>
</head>
<body>
<div>
<!-- Tabs -->
<ul class="tabs">
<li class="active"><a href="#home">Home</a></li>
<li><a href="#profile">Profile</a></li>
<li><a href="#messages">Messages</a></li>
<li><a href="#settings">Settings</a></li>
</ul>
<!-- Tab panes -->
<div class="tab-content">
<div class="tab-pane active" id="home" aria-expanded="true">Home Panel</div>
<div class="tab-pane" id="profile">Profile Panel</div>
<div class="tab-pane" id="messages">Messages Panel</div>
<div class="tab-pane" id="settings">Settings Panel</div>
</div>
<!-- Tabs -->
<ul class="tabs">
<li class="active"><a href="#home2">Home 2</a></li>
<li><a href="#profile2">Profile 2</a></li>
<li><a href="#messages2">Messages 2</a></li>
<li><a href="#settings2">Settings 2</a></li>
</ul>
<!-- Tab panes -->
<div class="tab-content">
<div class="tab-pane active" id="home2" aria-expanded="true">Home Panel 2</div>
<div class="tab-pane" id="profile2">Profile Panel 2</div>
<div class="tab-pane" id="messages2">Messages Panel 2</div>
<div class="tab-pane" id="settings2">Settings Panel 2</div>
</div>
</div>
<script>
(function(){
function getChildren(n, skipMe){
var r = [];
for ( ; n; n = n.nextSibling )
if ( n.nodeType == 1 && n != skipMe)
r.push( n );
return r;
};
function getSiblings(n) {
return getChildren(n.parentNode.firstChild, n);
}
function onTabClick(e){
e.preventDefault();
let otherLinks = getSiblings(e.target.parentNode);
let otherPanels = getSiblings(document.getElementById(e.target.href.split('#')[1]));
let siblings = otherLinks.concat(otherPanels);
// deactivate existing active tab and panel
for (let i=0; i < siblings.length; i++){
siblings[i].classList.remove('active');
siblings[i].setAttribute('aria-expanded', 'false');
}
// activate new tab
e.target.parentNode.classList.add('active');
// activate new panel
let panel = document.getElementById(e.target.href.split('#')[1]);
panel.getAttribute('aria-expanded') == 'true' ? panel.setAttribute('aria-expanded', 'false') : panel.setAttribute('aria-expanded', 'true');
}
let tabLinks = document.querySelectorAll('.tabs a');
for (let i=0; i < tabLinks.length; i++){
tabLinks[i].addEventListener('click', onTabClick, false);
}
})();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment