RuTrash Channel RuTrash Channel - 20 days ago 8
Javascript Question

javascript tabs not working correctly

I have a question. Everything works fine, but if I add more tabs, so "isVisible" class is added to all other tabs. How do I fix this problem?

HTML:

<div class="content">
<button class="nextTab">Next Tab</button>
<div class="tabs">
<div class="tabs__item isActive">
<p>1 Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
</div>
<div class="tabs__item">
<p>2 Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
</div>
</div>
</div>


Javascript (Babel)

(() => {
const tabs = document.querySelector('.tabs')
, tabsItem = document.querySelectorAll('.tabs__item')
, nextTab = document.querySelector('.nextTab')

nextTab.addEventListener('click', () => {
for(let i = 0; i < tabsItem.length; i++) {
tabsItem[i].classList.toggle('isActive')
}
})
})()

Answer

You should track a current tab index in order to be able to switch to next one.

(() => {
    const tabs = document.querySelector('.tabs')
        , tabsItem = document.querySelectorAll('.tabs__item')
        , nextTab = document.querySelector('.nextTab')
        , currentTab = 0;

    nextTab.addEventListener('click', () => {
      if (++currentTab > tabsItem.length - 1) currentTab = 0; 
      document.querySelector('.isActive').classList.remove('isActive'));
      tabsItem[currentTab].classList.add('isActive'))
    });
})()