Skip to main content

Implement Tabs Component

Problem

Implement a tabs component that can be used to switch between different content sections.

Solution

<section class="tabs">
<ul class="tab-headers">
<li class="tab-header active">Tab 1</li>
<li class="tab-header">Tab 2</li>
<li class="tab-header">Tab 3</li>
</ul>
<div class="tab-contents">
<div class="tab-content active">Content for Tab 1</div>
<div class="tab-content">Content for Tab 2</div>
<div class="tab-content">Content for Tab 3</div>
</div>
</section>
const tabs = document.querySelectorAll('.tabs');

tabs.forEach(tab => {
const tabHeaders = tab.querySelectorAll('.tab-header');
const tabContents = tab.querySelectorAll('.tab-content');

const showTab = (index) => {
tabHeaders.forEach((header, i) => {
header.classList.toggle('active', i === index);
});
tabContents.forEach((body, i) => {
body.classList.toggle('active', i === index);
});
}

tabHeaders.forEach((header, index) => {
header.addEventListener('click', () => showTab(index));
});

// Show the first tab by default
showTab(0);
});

Summary