Created
May 17, 2022 06:18
-
-
Save yitonghe00/f12a47769d36b27d1f94fc51b43ed6b3 to your computer and use it in GitHub Desktop.
This file contains 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
<tab-panel> | |
<div data-tabname="one">Tab one</div> | |
<div data-tabname="two">Tab two</div> | |
<div data-tabname="three">Tab three</div> | |
</tab-panel> | |
<script> | |
function asTabs(node) { | |
const tabList = document.createElement('div'); | |
const tabs = Array.from(node.children).map((child) => { | |
const button = document.createElement('button'); | |
button.textContent = child.getAttribute('data-tabname'); | |
const tab = { node: child, button }; | |
button.addEventListener('click', () => selectTab(tab)); | |
tabList.appendChild(button); | |
return tab; | |
}); | |
node.insertBefore(tabList, node.firstChild); | |
const selectTab = (selectedTab) => { | |
tabs.forEach((tab) => { | |
const selected = selectedTab === tab; | |
tab.node.style.display = selected ? '' : 'none'; | |
tab.button.style.backgroundColor = selected ? 'yellow' : ''; | |
}); | |
}; | |
selectTab(tabs[0]); | |
} | |
asTabs(document.querySelector("tab-panel")); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment