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 panelRequirements
- Render a
role="tablist"with one<button role="tab">per item, and onerole="tabpanel"per item. - Link them: each tab has
aria-controlspointing at its panel'sid, and each panel hasaria-labelledbypointing 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 (usehidden). - Clicking a tab selects it.
- Keyboard:
ArrowRightandArrowLeftselect and focus the next or previous tab, wrapping around;HomeandEndgo to the first and last tab. - Only the selected tab is in the Tab order (
tabIndex0); the others havetabIndex-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.