Build a Tab Switcher

Tabs share the same visual area but show different content. Use event delegation to wire all tabs in a single listener — the technique scales to dozens of tabs without slowing down.

Step 1 of 2

Tabs are linked to panels

A tab switcher has two parts:

  • Tab buttons in a row.
  • Panels — one per tab — only one of which is visible at a time.

The link is usually a shared identifier. Each button has data-tab="a"; each panel has id="a". When the user clicks a button, JS hides every panel except the one whose id matches the clicked button's data-tab.

Think of it this way: Like the tabs in a paper folder. Only one section is visible at a time, but all the content is filed in there. Pulling a tab brings that section to the front.
Tip

Event delegation means: attach one listener to the parent of all the buttons, then check inside the handler which child was clicked. Faster, cleaner, and works even when buttons are added later.