Last active
September 29, 2021 01:53
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- 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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Should work for almost any setup, regardless of JS-framework or CSS framework