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.
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.
<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>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.