Skip to content
jshacks.dev
Browser

Build an accessible tabs widget

Build tabs with the ARIA tablist pattern: roles, aria-selected, roving tabindex and arrow keys, in about thirty lines of plain JavaScript.

2 min read
Summarize in AI

Tabs look simple until a keyboard user arrives. The WAI-ARIA tabs pattern asks for roles, one tab stop, and arrow keys to move between tabs.

tabs.htmlHTML
<div role="tablist" id="tabs">
  <button role="tab" id="t1" aria-controls="p1" aria-selected="true">Code</button>
  <button role="tab" id="t2" aria-controls="p2" aria-selected="false" tabindex="-1">Output</button>
</div>
<div role="tabpanel" id="p1" aria-labelledby="t1">Code panel</div>
<div role="tabpanel" id="p2" aria-labelledby="t2" hidden>Output panel</div>
tabs.jsJavaScript
const tabs = [...document.querySelectorAll('[role="tab"]')];

function select(tab) {
  for (const t of tabs) {
    const active = t === tab;
    t.setAttribute('aria-selected', active);
    t.tabIndex = active ? 0 : -1;
    document.getElementById(t.getAttribute('aria-controls')).hidden = !active;
  }
  tab.focus();
}

document.querySelector('#tabs').addEventListener('click', (e) => {
  const tab = e.target.closest('[role="tab"]');
  if (tab) select(tab);
});

document.querySelector('#tabs').addEventListener('keydown', (e) => {
  const i = tabs.indexOf(document.activeElement);
  if (e.key === 'ArrowRight') select(tabs[(i + 1) % tabs.length]);
  if (e.key === 'ArrowLeft') select(tabs[(i - 1 + tabs.length) % tabs.length]);
});

Only the selected tab has tabindex="0", so Tab enters the list once and the arrows move within it. aria-selected tells a screen reader which tab is active, and hidden removes the other panels from the accessibility tree. Add Home and End keys if your list is long. If you do not need scripted switching, details elements need no JavaScript at all.

Share

More snippets

APIs

Fetch JSON and handle HTTP errors

Fetch JSON in the browser or Node.js 24 and throw on 404 or 500 yourself, because fetch only rejects on network failure and does not check the status.

1 min read
Browser

Find the closest ancestor with closest

Walk up from an element to the nearest ancestor that matches a selector with closest, which includes the element itself. Works in all modern browsers.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.