DEV Community

Arhan Khan
Arhan Khan

Posted on

Build a Tabs Component with JavaScript

Tabs are everywhere — settings pages, product details, documentation. They solve a simple problem: too much content for one screen. A good tabs component is about 20 lines of JavaScript, and it is one of the best beginner projects because it teaches you state in its simplest form.

What you are building

A row of tab buttons and a set of panels, where clicking a button shows its panel and hides the others.

The HTML: buttons linked to panels by data attributes

<div class="tabs">
  <button class="tab-btn active" data-tab="overview">Overview</button>
  <button class="tab-btn" data-tab="features">Features</button>
  <button class="tab-btn" data-tab="pricing">Pricing</button>
</div>

<div class="tab-panel" id="overview">Welcome to the overview.</div>
<div class="tab-panel hidden" id="features">Here are the features.</div>
<div class="tab-panel hidden" id="pricing">Here is the pricing.</div>
Enter fullscreen mode Exit fullscreen mode

The JavaScript: one active tab at a time

const buttons = document.querySelectorAll('.tab-btn');
const panels = document.querySelectorAll('.tab-panel');

buttons.forEach((btn) => {
  btn.addEventListener('click', () => {
    // Clear the old active state
    buttons.forEach((b) => b.classList.remove('active'));
    panels.forEach((p) => p.classList.add('hidden'));

    // Set the new active state
    btn.classList.add('active');
    document.querySelector('#' + btn.dataset.tab).classList.remove('hidden');
  });
});
Enter fullscreen mode Exit fullscreen mode

The pattern is always the same: clear everything, then activate one thing. You will see this "clear, then set" pattern in accordions, sliders, and navigation menus too.

The CSS: two classes carry the design

.hidden { display: none; }

.tab-btn.active {
  border-bottom: 2px solid #2563eb;
  color: #2563eb;
}
Enter fullscreen mode Exit fullscreen mode

Make it keyboard-friendly

<button class="tab-btn" data-tab="features" role="tab" aria-selected="false">Features</button>
Enter fullscreen mode Exit fullscreen mode

Adding role="tab" and updating aria-selected when a tab activates is a small change that makes your component usable for people who navigate with a keyboard or a screen reader.

The one thing to remember

Keep the button-to-panel link in one place — the data-tab attribute. If the link lives in two places, like matching array indexes in JavaScript, the day you reorder your tabs everything breaks silently.

Top comments (0)