Sikau

Web essentials · Day 11 · about 40 min

Project: Accessible accordion

A component that works for everyone.

A real component

Accordions (expand/collapse sections) are everywhere: FAQs, settings, menus. Build one that works with mouse, keyboard and screen readers — using real buttons, ARIA states, and arrow-key navigation between headers.

The accordion pattern

Building components that work for everyone isn't extra polish — it's part of the job. Following established patterns means less code, fewer bugs and fewer surprises for the people using it.

An accordion is a stack of headings, each with a button that shows or hides the panel below it. The pattern is well established, which is good news: screen reader users know what to expect when the structure follows the convention. Each heading contains a real <button>; the button has aria-expanded and aria-controls pointing at its panel; the panel has an id and is hidden when collapsed.

<h3>
  <button aria-expanded="false" aria-controls="faq-1">
    How long does delivery take?
  </button>
</h3>
<div id="faq-1" hidden>
  <p>About 30 minutes inside the Ring Road.</p>
</div>

With that structure, the JavaScript is small: one delegated click listener toggles the panel's hidden and flips aria-expanded. Keyboard support for Enter and Space comes free from the button.

The rest of this lesson

  • Arrow-key navigationexplain
  • Toggling a sectionorder
  • Wrapping aroundpredict
  • Accordion partsmatch
  • Build the accordionchallenge
  • Badge quizquiz
  • Unit 3 complete!recap

Continue this lesson free — run real code in your browser

Continue with Google

See all 16 lessons of Web essentials