Skip to content
jshacks.dev
Browser

Build an accessible accordion

Build an accordion from native details elements, close the others with the name attribute, and add a little JavaScript only where the browser does not.

1 min read
Summarize in AI

Before writing ARIA by hand, check whether <details> does the job. It is keyboard accessible, announces its expanded state to assistive technology, and needs no script to toggle.

accordion.htmlHTML
<details name="faq" open>
  <summary>What is a closure?</summary>
  <p>A function that keeps access to variables from where it was created.</p>
</details>
<details name="faq">
  <summary>What is hoisting?</summary>
  <p>Declarations are registered before the code in their scope runs.</p>
</details>
accordion.jsJavaScript
document.addEventListener('toggle', (event) => {
  const d = event.target;
  console.log(`${d.querySelector('summary').textContent}: ${d.open}`);
}, true);
Text
What is a closure?: false
What is hoisting?: true

Giving several details elements the same name makes them an exclusive group, so opening one closes the others. The attribute is defined in the HTML Standard and works in Chrome 120, Safari 17.2 and Firefox 130 or newer. The toggle event does not bubble, which is why the listener uses the capture phase on document.

Reach for a custom ARIA accordion only when you need animated height or content that must stay in the DOM while closed in a way details does not allow.

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.