Vanilla JavaScript Projects

Project 55, Website sections

Tabs and Accordion Kit

Two of the most used page parts on the web, built the right way: they work with a keyboard, screen readers understand them and they open smoothly.

Main API
ARIA tabs pattern
Animation
Web Animations API
Dependencies
None
Your browser
Checking

Tabs and accordion

Click a tab or use the arrow keys, Home and End. Open accordion items and choose whether one or many can be open.

Tabs

Wooden desk chair in a bright room

A solid oak desk chair with a woven seat. Made to order in 3 weeks.

Accordion

How it works

  1. Roving tabindexOnly the selected tab is in the Tab order. Arrow keys move selection, so one Tab press takes you into the panel.
  2. Link tabs and panelsaria-controls and aria-labelledby connect each tab to its panel, so screen readers announce them together.
  3. Animate real heightThe accordion measures scrollHeight and animates from 0 to that height with element.animate().
tabs.forEach((tab, i) => tab.onkeydown = (e) => {
  const next = { ArrowRight: i + 1, ArrowLeft: i - 1, Home: 0, End: tabs.length - 1 }[e.key];
  if (next === undefined) return;
  select(tabs[(next + tabs.length) % tabs.length]);
});
function select(tab) {
  tabs.forEach((t) => {
    const on = t === tab;
    t.setAttribute("aria-selected", on);
    t.tabIndex = on ? 0 : -1;
    document.getElementById(t.getAttribute("aria-controls")).hidden = !on;
  });
  tab.focus();
}