Skip to content

Instantly share code, notes, and snippets.

@sroehrl
Last active September 29, 2021 01:53
Show Gist options
  • Save sroehrl/2c1eaf2f0327f2869f91ec81ac4be18e to your computer and use it in GitHub Desktop.
Save sroehrl/2c1eaf2f0327f2869f91ec81ac4be18e to your computer and use it in GitHub Desktop.
Simple vanilla JavaScript tab-system ( for static pages or CSS only frameworks like bulma or tailwind)
const tabSystem = {
init(){
document.querySelectorAll('.tabs-menu').forEach(tabMenu => {
Array.from(tabMenu.children).forEach((child, ind) => {
child.addEventListener('click', () => {
tabSystem.toggle(child.dataset.target);
});
if(child.className.includes('is-active')){
tabSystem.toggle(child.dataset.target);
}
});
});
},
toggle(targetId){
document.querySelectorAll('.tab-content').forEach(contentElement=>{
contentElement.style.display = contentElement.id === targetId ? 'block' : 'none';
document.querySelector(`[data-target="${contentElement.id}"]`).classList[contentElement.id === targetId ? 'add' : 'remove']('is-active');
})
},
};
tabSystem.init();
<!-- class "tabs-menu" makes any direct children potential triggers -->
<ul class="tabs-menu">
<!-- class "is-active marks initially opened tab-content". data-target holds the id of the target tab-content -->
<li class="is-active" data-target="first-tab"><a>Tab one</a></li>
<li data-target="second-tab"><a>Tab two</a></li>
</ul>
<!-- any element with the class "tab-content" can be triggered (specify by ID) -->
<div class="tab-content" id="first-tab">
<p>This is tab 1</p>
</div>
<div class="tab-content" id="second-tab">
<p>This is tab 2</p>
</div>
@sroehrl
Copy link
Author

sroehrl commented Dec 13, 2019

Should work for almost any setup, regardless of JS-framework or CSS framework

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment