DEV Community

Haruka Kakiuchi
Haruka Kakiuchi

Posted on

Tabs

<div class="tabs_wrap">
  <div class="tabs_container">
    <button class="btn tab tab--1 tab--active" data-tab="1">
      tab button 1
    </button>
    <button class="btn tab tab--2 tab--active"  data-tab="2">
      tab button 2
    </button>
  </div>
  <div class="content content--1 content--active">
    <div>
      contents 1
    </div>
  </div>
  <div class="content content--2 content--active">
    <div>
      contents 2
    </div>
  </div>
</div>  
Enter fullscreen mode Exit fullscreen mode
const tabs = document.querySelectorAll('.tab');
const tabsContainer = document.querySelector('.tabs_container');
const tabsContent = document.querySelectorAll('.content');
Enter fullscreen mode Exit fullscreen mode
tabsContainer.addEventListener('click', function (e) {
  const clicked = e.target.closest('.tab');

  // Guard clause
  if (!clicked) return;

  // Remove active classes
  tabs.forEach(t => t.classList.remove('tab--active'));
  tabsContent.forEach(c => c.classList.remove('content--active'));

  // Activate tab
  clicked.classList.add('tab--active');

  // Activate content area

 document.querySelector(`.content-${clicked.dataset.tab}`).classList.add('content--active');
});
Enter fullscreen mode Exit fullscreen mode

Avoid using forEach to attach events to each tab. Instead, leverage event bubbling to set an event listener on the parent element and determine which child element it corresponds to.

Top comments (0)