FrontendPro

24Implement a simple tab switcher with HTML, CSS and JavaScript

easyAbout 15 minutesCodingdomaccessibilitykeyboardui

Problem

Implement createTabs(container, tabs). tabs is an array of { label, content }. Render an accessible tab switcher into container and return { select(index), selectedIndex }.

const api = createTabs(document.getElementById("root"), [
  { label: "HTML", content: "Structure" },
  { label: "CSS", content: "Presentation" },
  { label: "JavaScript", content: "Behaviour" },
]);
api.select(2); // shows the JavaScript panel

Requirements

  • Render a role="tablist" with one <button role="tab"> per item, and one role="tabpanel" per item.
  • Link them: each tab has aria-controls pointing at its panel's id, and each panel has aria-labelledby pointing at its tab. Ids must be unique, even with several tab switchers on the page.
  • The selected tab has aria-selected="true"; others "false". Only the selected panel is visible (use hidden).
  • Clicking a tab selects it.
  • Keyboard: ArrowRight and ArrowLeft select and focus the next or previous tab, wrapping around; Home and End go to the first and last tab.
  • Only the selected tab is in the Tab order (tabIndex 0); the others have tabIndex -1.

Try it yourself

Write your solution, run it, then submit to check it against the tests.

App.jsxReact + DOM

Step-by-step

Use a module-level counter, so the second tab switcher on the page gets tabs-2-… ids. ARIA links break silently when ids repeat.

Unlock the full solution

What's inside

  • Step-by-step
  • Approach
  • Solution
  • Complexity
  • Edge cases
  • Follow-up questions
  • Tests

Includes 3 code listings, 5 edge cases, 4 follow-up questions.

One-time payment by UPI, card or net banking. Launch price.

All 150 answersOne payment, yours forever