DEV Community

ktr92
ktr92

Posted on

[html js] Tabs content toggle

<div data-tabs="tabs">
    <div class="tabs__nav" data-headertabs="tabs_id">
        <ul>
            <li class="active">1</li>
            <li class="">2</li>
        </ul>
    </div>
    <div class="tabs__wrapper" data-tabswrapper="tabs_id">
        <div class="tabs__content active" data-contenttabs="tabs_id">
            1
        </div>
        <div class="tabs__content " data-contenttabs="tabs_id">
            2
        </div>
    </div>
</div>

Enter fullscreen mode Exit fullscreen mode
document.querySelector('[data-headertabs]').addEventListener('click', function(e) {
    const el = e.target
    if (el.tagName === 'LI') {
        if (!el.classList.contains('active')) {
            let index = Array.from(el.parentNode.children).indexOf(el)

            document.querySelectorAll('[data-headertabs] li').forEach(item => {
                item.classList.remove('active')
            })
            el.classList.add('active')

            document.querySelectorAll('[data-contenttabs]').forEach(item => {
                item.classList.remove('active')
            })
            const items = Array.from(document.querySelector('[data-tabswrapper]').children)
            items[index].classList.add('active')
        }
    }
})
Enter fullscreen mode Exit fullscreen mode
[data-contenttabs] {
  display: none; 
}

[data-contenttabs].active {
  display: block; 
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)