An accessible accordion
Build an accessible accordion web component: the ARIA pattern, details and summary with name, real headings, a synced open attribute, and the right keys.
- 01Check an accordion against the ARIA patternFind the heading, the button, its expanded state, and the panel it controls in Chrome's accessibility tree.
- 02Pick details or your own elementUse
<details>and<summary>, withnamefor one-at-a-time, and buildtea-detailswhen each question must be a heading. - 03Keep an open attribute honestReflect a boolean
openattribute and property both ways with a guard, and support Enter, Space, and Tab without arrow keys.
How do you build an accessible accordion?
Leaf and Kettle's FAQ page has a list of questions, like "How hot should the water be?" Each answer stays folded away until you open it. Meena uses NVDA, a screen reader. On a long page, she presses H to jump from heading to heading. Will the questions turn up? And will she hear which answers are open?
An accessible accordion is a stack of headings, each holding one button. The button says whether its panel is expanded, and points at that panel. Enter or Space opens and closes it, and Tab moves on. HTML's <details> and <summary> give you most of this with no script. You build your own when each question must be a real heading.
Here is the pattern by hand, with two questions:
<h2>Tea FAQ</h2><h3><button aria-expanded="false" aria-controls="water">How hot should the water be?</button></h3><div id="water" hidden>About 80 degrees for green tea.</div><h3><button aria-expanded="false" aria-controls="steep">How long should it steep?</button></h3><div id="steep" hidden>Two minutes for sencha. Longer makes it bitter.</div><script> for (const button of document.querySelectorAll("h3 > button")) { button.addEventListener("click", () => { const open = button.ariaExpanded !== "true"; button.ariaExpanded = String(open); document.getElementById(button.getAttribute("aria-controls")).hidden = !open; console.log(button.textContent, open ? "opened" : "closed"); }); }</script>- Line 1 is the heading for the whole FAQ.
- Lines 2 and 4 are the questions. Each is an
h3that holds only a button. Each button starts witharia-expanded="false", and itsaria-controlsnames the box with its answer. - Lines 3 and 5 are the answers, hidden for now.
- Lines 8 to 13 run on each click. Line 10 flips the state through the button's
ariaExpandedproperty. Line 11 shows or hides the answer. Line 12 prints what happened.
Click the first question. It prints How hot should the water be? opened. Press Tab, then Enter: How long should it steep? opened.
Chrome's accessibility tree is the version of the page that screen readers read, as lesson 13.1 showed. Here it is after the first click:
heading "Tea FAQ", level: 2
heading "How hot should the water be?", level: 3
button "How hot should the water be?", expanded: true
heading "How long should it steep?", level: 3
button "How long should it steep?", expanded: falseBoth questions are headings at level 3. Inside each one is a button with its state. That's what Meena needs. H finds every question, and NVDA says expanded or collapsed.
aria-controls.Leaf and Kettle keeps loose tea in a cabinet of drawers. Each drawer has a label on the front, and a handle under the label. You read the labels to find the tea you want. You pull the handle to open that drawer, and push it to close it.
- In real life: The label on the front of a drawer
- In JavaScript: The heading
- In real life: The drawer's handle
- In JavaScript: The button
- In real life: A drawer pulled out, or pushed in
- In JavaScript:
aria-expanded="true"or"false" - In real life: The tea inside the drawer
- In JavaScript: The panel
An accordion is a stack of headings, each holding a button that shows or hides its panel. The button carries aria-expanded and aria-controls. Native <details> does the job when the questions don't need to be headings. A custom element does it when they do.
Why it matters: a screen reader can only say what the tree holds. With headings and states, Meena can find each question and know what's open.
What does the ARIA accordion pattern require?
The ARIA Authoring Practices Guide, the APG, has a page for each common widget, as lesson 14.3 showed for tabs. Its accordion pattern names two parts. An accordion header is the question you click. An accordion panel is the answer it shows or hides. Then it asks for these:
- The header's title is inside an element with the role button.
- The button is wrapped in a heading, at a level that fits the page. An
h1toh6will do. The button is the only thing inside the heading. - The button has
aria-expanded: true while its panel shows, and false while it's hidden. - The button has
aria-controls, set to the id of its panel. - If an open panel can't be closed, its button has
aria-disabled="true". Some accordions keep one panel open at all times. - Each panel may have the role region, named by its button through
aria-labelledby. That part is optional.
Why a heading around a button? Try four ways to mark up two questions, and read the tree under each:
<h2>Tea FAQ</h2><button aria-expanded="true" aria-controls="water">How hot should the water be?</button><div id="water">About 80 degrees for green tea.</div><button aria-expanded="false" aria-controls="steep">How long should it steep?</button><div id="steep" hidden>Two minutes for sencha.</div>heading "Tea FAQ", level: 2
button "How hot should the water be?", expanded: true
button "How long should it steep?", expanded: falseEach button says whether its answer is expanded. But the tree has no heading for either question, so a screen reader's heading keys skip them.
- Buttons only: two buttons with their states, and no headings. H skips both questions.
- role="button" on the heading: the tree is the same as buttons only. The role replaced the heading. Heydon Pickering warns against exactly this in Collapsible Sections.
- A heading around each button: two headings at level 3, each with its button.
- Plus a region: the open answer becomes a region named after its question. Chrome also links the button to the region, and the region back to the button.
So when is a region worth it? The APG says to skip it when more than about six panels can be open at once. Each region is a landmark, and too many crowd a screen reader's list of landmarks. A region helps most when a panel holds headings of its own, or another accordion. Chrome's accordion guide adds: don't wrap every small accordion in a region.
One rule is argued about, as it was for tabs. Chrome's guide says aria-controls is optional, because screen readers gain nothing from it. The APG still lists it, and so does its example. This lesson keeps it.
Why it matters: the heading is how people find a question, and the button's state is how they know what's open.
Can you build an accordion with details and summary?
Yes, and often you should. A <details> element is a box that opens and closes. Its first child, a <summary>, is the part you click. Lesson 1.1 opened its hidden shadow root. The browser gives it a button, a state, and the keys, with no script. Chrome's guide says to build accordions from a set of details elements first.
One attribute makes a set of them open one at a time. Give them all the same name:
<h2>Tea FAQ</h2><details name="faq"> <summary>How hot should the water be?</summary> <p>About 80 degrees for green tea.</p></details><details name="faq"> <summary>How long should it steep?</summary> <p>Two minutes for sencha.</p></details><details name="faq"> <summary>Can I reuse the leaves?</summary> <p>Yes. Oolong brews well two or three times.</p></details><script> for (const details of document.querySelectorAll("details")) { const question = details.querySelector("summary").textContent; details.addEventListener("toggle", (event) => console.log(question, event.newState)); }</script>- Lines 2, 6, and 10 are three details, all with
name="faq". - Lines 3, 7, and 11 are their summaries: the questions.
- Lines 15 to 18 print every
toggleevent: the question, then open or closed.
Click the first question: How hot should the water be? open. Now click the second. It prints two lines, How long should it steep? open, then How hot should the water be? closed. The browser closed the first one for you. Press Tab to reach a summary, then Enter or Space. Both keys open and close it.
The HTML Standard calls this an exclusive accordion: at most one details in a name group is open. MDN adds that the details don't have to sit next to each other. The standard also warns that one at a time can frustrate people who want to compare two answers. Chrome's guide adds that content jumping out of view hurts people who use a screen magnifier. So use name only when one at a time really helps.
The toggle event
toggle fires after a details opens or closes. Its newState says which. Three things to know:
- It doesn't bubble. Listen on each details, as line 17 does, or on a parent in the capture phase.
- Changes made in a row fire one event. After
details.open = true, thenfalse, thentrue, Chrome fires onetoggle. - Details have no
beforetoggleevent. That one is for popovers and dialogs, which come in lesson 14.5.
Here is Chrome's tree after the first click:
heading "Tea FAQ", level: 2
group (no name)
DisclosureTriangleGrouped "How hot should the water be?", expanded: true
group (no name)
DisclosureTriangleGrouped "How long should it steep?", expanded: false
group (no name)
DisclosureTriangleGrouped "Can I reuse the leaves?", expanded: falseEach details is a group. Chrome calls a summary a DisclosureTriangle, and DisclosureTriangleGrouped when its details has a name. Each one has its expanded state. Now look for headings. Only Tea FAQ is one. Meena's H key would skip every question.
Find in page opens a closed answer
When you search a page with Ctrl+F, or Command+F on a Mac, the browser searches closed details too. The HTML Standard says it then opens the details that holds the match. A link to an id inside a closed details opens it the same way. An answer hidden with display: none can't be found at all. Safari opens the details on a match, but doesn't scroll to it.
Name groups and shadow roots
The standard has one more rule for name. Two details are in the same group only if they're in the same tree. A shadow root is a tree of its own. So where should a component's details live? Try three places:
<details name="faq"><summary>How hot should the water be?</summary>About 80 degrees for green tea.</details><details name="faq"><summary>How long should it steep?</summary>Two minutes for sencha.</details>Open the first question, then the second. The first one closes: both details are in the page's tree and share the name faq.
- In the page: the first closes.
- Slotted into a shadow root: the first closes. The details are still the page's own children. A slot only changes where they show, as lesson 13.1 showed.
- Each in its own shadow root: both stay open.
name only groups details in the same tree. In the page, opening the second closed the first. In two shadow roots, both stayed open.An old car radio has a row of station buttons. Push one in, and the one that was in pops out. The car parked next to yours has its own radio. Pushing a button in your car never pops one out in theirs.
- In real life: One car's row of station buttons
- In JavaScript: Details with the same name in one tree
- In real life: Pushing a button in
- In JavaScript: Opening a details
- In real life: The other button popping out
- In JavaScript: The browser closing the open one
- In real life: The radio in the next car
- In JavaScript: A details in another shadow root
Real components meet this. Web Awesome's wa-details puts a details in each shadow root, and those details can't group. So its own code, closeOthersWithSameName(), closes the others itself.
The kit's first accordion keeps the details in the page instead. tea-accordion wraps the page's own details, and has no shadow root:
<tea-accordion exclusive> <details><summary>How hot should the water be?</summary>About 80 degrees for green tea.</details> <details><summary>How long should it steep?</summary>Two minutes for sencha.</details></tea-accordion><tea-accordion exclusive> <details><summary>When will my order arrive?</summary>In two or three days.</details> <details><summary>Can I send it back?</summary>Yes, within 30 days.</details></tea-accordion><script type="module"> import "./tea-kit/index.js"; for (const details of document.querySelectorAll("details")) console.log(details.name);</script>- Lines 1 and 5 are two accordions, each with the boolean attribute
exclusive. - Line 11 prints the name of every details.
It prints tea-accordion-1 twice, then tea-accordion-2 twice. Each accordion made a name of its own. Open a question in each: both stay open. Then open the other question in the first: its first answer closes. Chrome's guide warns not to reuse a name elsewhere on the page, and a new name for each accordion makes sure of that. Here is the part that sets them:
#group() {
for (const details of this.querySelectorAll(":scope > details")) {
if (this.exclusive) details.name = this.#name;
else if (details.name === this.#name) details.removeAttribute("name");
}
}- Line 2 visits each details that is a direct child.
- Line 3 gives it the accordion's name. Line 4 takes the name off again when
exclusivegoes away.
A MutationObserver runs this again when the page adds a details, as lesson 5.5 did for the tea menu. The word exclusive comes from the HTML Standard, and Open UI's accordion research uses it too. Many design systems it lists make one at a time an option, off by default, and so does the kit.
Can a summary element be a heading?
No, and that's the one thing details can't give you. Meena wants each question to be a heading. Can you put a heading in a summary, or a summary in a heading? Try both, beside the kit's answer:
<details> <summary><h3>How hot should the water be?</h3></summary> <p>About 80 degrees for green tea.</p></details>group (no name)
DisclosureTriangle "How hot should the water be?", expanded: false
heading "How hot should the water be?", level: 3Chrome keeps the heading, but inside the summary. The APG wants it the other way round: the heading around the button.
- h3 inside the summary: Chrome keeps the heading, but inside the summary's button. Chrome's guide warns that JAWS and TalkBack treat a summary as a button, and drop any heading inside it. MDN's summary page gives the same warning.
- h3 around the summary: the summary isn't the first child of its details any more, so it stops being the summary. Chrome shows a summary of its own, named Details, and hides the question with the answer.
- tea-details: a heading at level 3, holding a button.
HTML's rules close the last door. The W3C's ARIA in HTML allows no role at all on a summary, so role="heading" is out too. And HTML-AAM, which says how browsers describe each element to screen readers, maps a summary to a button on Windows.
<summary> ends up inside a button, and JAWS and TalkBack drop it. The APG wants the heading on the outside, holding the button.A good book lists its chapters on a contents page, and you turn straight to the one you want. If a chapter's title is only printed inside a picture, it never makes the contents page. You'd have to leaf through to find it.
- In real life: The chapter titles on the contents page
- In JavaScript: The headings in the tree
- In real life: Turning straight to a chapter
- In JavaScript: Pressing H in a screen reader
- In real life: A chapter title printed inside a picture
- In JavaScript: A heading inside a summary
So Chrome's guide says to build a custom accordion only when each item needs its own heading. A FAQ is the usual case, or a long reference page. Everywhere else, use details. Why it matters: picking details when you can saves you every line of script, and picking your own element when you must keeps the headings.
Building an accordion web component with real headings
The kit's second accordion is tea-details. It works like details: an open attribute, an open property, and a toggle event. But it builds the APG's shape in its shadow root. Here is the tea FAQ again:
<h2>Tea FAQ</h2><tea-details level="3"> <span slot="summary">How hot should the water be?</span> <p>About 80 degrees for green tea.</p></tea-details><tea-details level="3"> <span slot="summary">How long should it steep?</span> <p>Two minutes for sencha.</p></tea-details><script type="module"> import "./tea-kit/index.js"; for (const details of document.querySelectorAll("tea-details")) { const question = details.querySelector('[slot="summary"]').textContent; details.addEventListener("toggle", (event) => console.log(question, event.newState)); }</script>- Lines 2 and 6 are two questions at heading level 3, under the h2 on line 1.
- Lines 3 and 7 put each question in the summary slot. Lines 4 and 8 are the answers.
- Lines 12 to 15 print every toggle, as the details page did.
Click the first question: How hot should the water be? open. Press Tab, then Enter, then Space. The second question prints open, then closed. Here is Chrome's tree after the first click:
heading "Tea FAQ", level: 2
heading "How hot should the water be?", level: 3
button "How hot should the water be?", expanded: true
heading "How long should it steep?", level: 3
button "How long should it steep?", expanded: falseIt's the same tree as the hand-built page in the overview. Now H finds every question. Here is the shadow root:
const template = document.createElement("template");
template.innerHTML = `
<div role="heading" aria-level="2" part="heading">
<button part="button" aria-expanded="false" aria-controls="panel">
<span class="marker" aria-hidden="true"></span><slot name="summary"></slot>
</button>
</div>
<div class="panel" id="panel" part="panel" hidden="until-found"><slot></slot></div>`;- Line 3 is the heading: a box with the role heading. Its
aria-levelstarts at 2, the level a heading has when it doesn't say. - Line 4 is a real button, the only thing in the heading. It starts collapsed, and its
aria-controlsnames the panel's id. - Line 5 is a + or − marker, hidden from screen readers, then the summary slot. The slotted question names the button.
- Line 8 is the panel around the answer,
hidden="until-found"for now.
Every id here lives in one shadow root. Lesson 13.3 showed that ids only work inside one tree, and nothing here crosses out of it. Why not give the tag itself the role heading, from its internals, as lesson 13.2 did for the switch? A heading may hold only its button, and the tag holds the answer too.
The level comes from an attribute:
attributeChangedCallback(name, oldValue, newValue) {
if (name === "open") this.open = newValue !== null;
if (name === "level") {
const level = toInteger(newValue, 2, 1);
this.shadowRoot.querySelector('[role="heading"]').ariaLevel = String(level <= 6 ? level : 2);
}
}- Line 2 hands
opento the setter. The next section is about that. - Lines 4 and 5 turn the
levelattribute into the heading'sariaLevel: a whole number from 1 to 6, or else 2.toInteger()comes from the kit's parsers in lesson 5.2.
Keeping closed answers findable
hidden="until-found" hides the panel the way hidden does, but find in page can still search it. When a match is inside, the HTML Standard says the browser fires beforematch on the panel, then removes the attribute. A link to an id inside does the same. So the details listens:
this.shadowRoot.querySelector("button").addEventListener("click", () => {
this.open = !this.open;
});
this.shadowRoot.querySelector(".panel").addEventListener("beforematch", () => {
this.open = true;
});- Lines 1 to 3: a click on the button flips the answer open or closed.
- Lines 4 to 6:
beforematchopens it, so the button says expanded too.
Chrome's guide does the same for its own custom accordion. Where a browser doesn't know until-found, the attribute acts as plain hidden. The answer can't be found then, but the accordion still works. Safari opens the answer on a match, but doesn't scroll to it.
How do you keep an open attribute and property in sync?
tea-details copies the API of details. You write open in HTML, or set open from script. Lesson 5.2 showed that open is a boolean attribute: there means open, missing means closed. details.open = true writes open="", and false removes it. MDN's page on attribute reflection says the same.
Lesson 5.1 showed two designs. This one keeps the value in a private field. So each side calls the other: the setter writes the attribute, and the attribute's callback calls the setter. Here is the setter:
set open(value) {
const open = Boolean(value);
if (open === this.#open) return;
this.#open = open;
this.toggleAttribute("open", open);
this.shadowRoot.querySelector("button").ariaExpanded = String(open);
const panel = this.shadowRoot.querySelector(".panel");
if (open) panel.removeAttribute("hidden");
else panel.setAttribute("hidden", "until-found");
this.dispatchEvent(new ToggleEvent("toggle", { oldState: open ? "closed" : "open", newState: open ? "open" : "closed" }));
}- Line 2 turns any value into true or false, as
Boolean()does. - Line 3 is the guard. If the value didn't change, the setter stops here.
- Line 5 writes the attribute.
toggleAttribute()adds it for true and removes it for false. - Lines 6 to 9 update the button and the panel.
- Line 10 fires
toggle, aToggleEventlike the one details fires, witholdStateandnewState.
Why the guard? Lesson 3.4 showed a setter that calls setAttribute(), and a callback that calls the setter. They call each other until Chrome throws a RangeError. toggleAttribute() breaks that circle: the second time, it changes nothing, so no callback runs. But the setter still runs twice. Try a teammate's copy, with and without the guard:
<faq-item>How hot should the water be?</faq-item><script> class FaqItem extends HTMLElement { static observedAttributes = ["open"]; #open = false; get open() { return this.#open; } set open(value) { const open = Boolean(value); // No guard on this line. this.#open = open; this.toggleAttribute("open", open); console.log("toggle:", open ? "open" : "closed"); } attributeChangedCallback(name, oldValue, newValue) { this.open = newValue !== null; } } customElements.define("faq-item", FaqItem); const item = document.querySelector("faq-item"); item.open = true; item.setAttribute("open", ""); item.removeAttribute("open");</script>Setting the property prints toggle twice: once from the callback the setter caused, and once more when the setter finishes. Writing the same attribute again prints a third time, though nothing changed.
- Line 9 is the only line that changes. Line 14 is the callback, which calls the setter.
- Lines 18 to 20 set the property, write the same attribute again, then remove it.
- Without the guard: four lines for two changes. Line 18 prints
toggle: opentwice, once from the callback. Line 19 prints it a third time. - With the guard:
toggle: open, thentoggle: closed.
Line 19 shows the guard's second job. Lesson 3.4 showed that setAttribute() runs the callback even when the value is the same. Without the guard, the page hears about a change that never happened.
toggle fires once.Leaf and Kettle's door has a chime. It rings when the door swings open. If Ravi pushes on a door that's already open, nothing moves, so nothing rings. The chime only tells the shop about real changes.
- In real life: The door swinging open
- In JavaScript:
openchanging from false to true - In real life: The chime
- In JavaScript: The
toggleevent - In real life: Pushing on a door that's already open
- In JavaScript: Setting
opento true again - In real life: The chime staying quiet
- In JavaScript: The guard returning at once
tea-accordion's exclusive needs no guard. Its getter reads the attribute, its setter only writes it, and its callback only regroups. That's lesson 5.1's first design, with one place for the value.
One rule from lesson 5.2 shapes the name. A boolean attribute must mean off when it's missing, because HTML can't turn one off. Heydon's toggle-section read open="true" and open="false". The kit follows HTML's rule instead, as details does. Why it matters: the attribute, the property, the button, and the event always agree, and each real change is announced once.
Which keys should an accordion support?
The APG lists only these:
- Enter or Space on a header opens a closed panel, or closes an open one. In a one-at-a-time accordion, opening one closes the other.
- Tab and Shift+Tab move to the next or the previous thing that takes focus. Every one of them in the accordion is in the page's Tab order: each header, and anything inside an open panel.
That's all. A real button gives you Enter and Space, and so does a summary. Neither the hand-built page nor tea-details has a line of key code.
Older tutorials add the arrow keys, Home, and End between headers. Google's HowTo: Components accordion did, with a roving tabindex. The APG once listed them as optional, and has since removed them. The issue behind it said that with Up and Down moving between headers, a keyboard user couldn't scroll the page to read the answer they'd just opened. Try both:
<style>h3 { margin: 0; font-size: 1em; } .more { height: 600px; }</style><div class="faq"> <h3><button aria-expanded="false">How hot should the water be?</button></h3> <h3><button aria-expanded="false">How long should it steep?</button></h3> <h3><button aria-expanded="false">Can I reuse the leaves?</button></h3></div><p><a href="/teas">Shop teas</a></p><p class="more">More questions soon.</p><script type="module"> import { RovingFocus } from "./tea-kit/roving.js"; document.addEventListener("focusin", (event) => console.log("Focus:", event.target.textContent)); addEventListener("scroll", () => console.log("The page scrolled"), { once: true }); // No arrow keys: each question is its own Tab stop.</script>Down Arrow scrolls the page, as it does anywhere else. Tab goes to the next question: every question is its own Tab stop.
- Lines 3 to 5 are three questions. Line 7 is a link after them.
- Line 11 prints each focus. Line 12 prints the first scroll. In the second choice, lines 13 and 14 add lesson 14.2's
RovingFocus.
- Today's APG: Down Arrow prints
The page scrolled. Tab moves to the second question. - Arrow keys between questions: Down Arrow moves to the second question, and nothing scrolls. Tab jumps to
Shop teas, because the other questions are no longer Tab stops.
Lesson 14.2's roving tabindex is for widgets that act as one control, like a toolbar or tabs. An accordion isn't one. Each header is a control of its own, so each is a Tab stop. Chrome's guide says it too: no arrow keys, no roving tabindex, no Home or End.
The tea shop's tasting rooms open off one corridor. You walk past each door and open the one you want. You can always walk on down the corridor, whatever door is open. Nobody blocks the corridor to make you use a side passage.
- In real life: Walking on to the next door
- In JavaScript: Tab
- In real life: Turning a door's handle
- In JavaScript: Enter or Space
- In real life: Walking on down the corridor to read the signs
- In JavaScript: The arrow keys scrolling the page
Then listen to it, with the VoiceOver and NVDA steps from lesson 14.3. In NVDA's browse mode, press H to land on a question. Listen for the heading level, the button, and collapsed. Press Enter, and listen for expanded. The button also shows the kit's focus ring from lesson 14.1, through the base sheet's :focus-visible rule. Why it matters: the keys people already know keep working, and so does scrolling.
Adding an accordion to the tea kit
The kit's new version is kitAfter144. Two files are new, and every older file stays as it was:
tea-kit/tea-accordion.jsistea-accordion: the page's own details, one at a time withexclusive.tea-kit/tea-details.jsistea-details: a question that's a real heading, withopen,level, and atoggleevent.
Here the kit's accordion opens with a tea card inside:
<link rel="stylesheet" href="tea-kit/tokens.css"><tea-details open> <span slot="summary">Which tea should I try first?</span> <tea-card name="Sencha" price="4"></tea-card></tea-details><tea-details> <span slot="summary">How hot should the water be?</span> <p>About 80 degrees for green tea.</p></tea-details><script type="module"> import "./tea-kit/index.js"; for (const details of document.querySelectorAll("tea-details")) { details.addEventListener("toggle", (event) => console.log(event.newState, details.open)); }</script>- Line 2 starts open. Line 4 puts a kit
tea-cardin the answer. - Line 13 prints each change, then the open property.
Click the first question: closed false. Click it again: open true. Press Tab, and focus goes into the card's - button. Anything that takes focus in an open answer is in the Tab order, as the APG says. Chrome's tree as the page loads:
heading "Which tea should I try first?", level: 2
button "Which tea should I try first?", expanded: true
heading "Sencha", level: 3
button "One cup less"
button "One cup more"
button "Add 1 Sencha"
heading "How hot should the water be?", level: 2
button "How hot should the water be?", expanded: falseThere's no level here, so the questions are at level 2. The card's own heading sits under them, at level 3. Read each row of the table across:
| What you want to know | The APG's markup by hand | details and summary | tea-details |
|---|---|---|---|
| Is each question a heading? | Yes. An h3 holds the button. | No. The summary acts as a button, and some screen readers drop a heading inside it. | Yes, at the level you give it. |
| Which keys work? | Enter, Space, and Tab, from the real button. | Enter, Space, and Tab, from the summary. | Enter, Space, and Tab, from the real button. |
| Can only one answer open at a time? | Only with your own script. | Yes. Give the details one name. | Only with your own script, as exercise 6 shows. |
| Can find in page reach a closed answer? | Only if the answer is hidden until found. | Yes. The browser opens the details. | Yes. Its answer is hidden until found. |
- A settings page with a few short notes that open and close.
- A long FAQ where screen reader users jump from question to question by heading.
- Only one answer may be open at a time.
- The questions must open and close before any script loads.
- A reference page where each item is a section with its own heading in the outline.
Sort each page by what Chrome's accordion guide and the APG point to.
The JSDoc and custom-elements.json document both tags. For the keyboard events behind Enter and Space, see Keyboard and focus on the JavaScript path. For the capture phase that exercise 6 uses, see Bubbling and capturing.
Common mix-ups
- "An accordion should move between headers with the arrow keys." No. The APG lists Enter, Space, and Tab. It removed the arrows, because they stopped people scrolling.
- "aria-expanded goes on the panel." No. It goes on the button, the control people use to change it.
- "A heading inside a summary makes the question a heading." No. The heading ends up inside a button, and JAWS and TalkBack drop it.
- "role="button" on an h3 keeps both roles." No. The role replaces the heading. Put a button inside the heading instead.
- "Details with the same name close each other anywhere on the page." No. Only in the same tree. Each shadow root is a group of its own.
- "toggleAttribute() makes the guard pointless." No. It stops the endless loop, but without the guard the setter still runs twice and fires two events.
- "Every panel should be a region." No. It's optional, and the APG says to skip it when more than about six panels can be open.
- "open="false" closes it." No.
openis a boolean attribute: if it's there at all, the answer is open.
Practice exercises
For each one, ask where the heading is, which element holds the state, and how many real changes happen.
Click How hot should the water be?, then Can I reuse the leaves?. Which question is open at the end?
<h2>Tea FAQ</h2><details name="faq"> <summary>How hot should the water be?</summary> <p>About 80 degrees for green tea.</p></details><details name="faq"> <summary>How long should it steep?</summary> <p>Two minutes for sencha.</p></details><details name="faq"> <summary>Can I reuse the leaves?</summary> <p>Yes. Oolong brews well two or three times.</p></details><script> for (const details of document.querySelectorAll("details")) { const question = details.querySelector("summary").textContent; details.addEventListener("toggle", (event) => console.log(question, event.newState)); }</script>Can I reuse the leaves? The page prints How hot should the water be? open, Can I reuse the leaves? open, then How hot should the water be? closed. The browser closed the first when the third opened.
The page sets the kit's details open three times. How many lines does it print?
<tea-details> <span slot="summary">How hot should the water be?</span> <p>About 80 degrees for green tea.</p></tea-details><script type="module"> import "./tea-kit/index.js"; const details = document.querySelector("tea-details"); details.addEventListener("toggle", (event) => console.log("toggle:", event.newState)); details.open = true; details.open = true; details.setAttribute("open", "");</script>1 line: toggle: open. Line 10 sets the same value again, and line 11 writes an attribute that's already there. The guard returns both times, so toggle fires once.
A teammate's question opens and closes, but a screen reader never says expanded. Which element should carry aria-expanded?
<h3><button aria-controls="water">How hot should the water be?</button></h3><div id="water" aria-expanded="false" hidden>About 80 degrees for green tea.</div><script> const button = document.querySelector("button"); const answer = document.getElementById("water"); button.addEventListener("click", () => { answer.hidden = !answer.hidden; answer.ariaExpanded = String(!answer.hidden); });</script><h3><button aria-expanded="false" aria-controls="water">How hot should the water be?</button></h3><div id="water" hidden>About 80 degrees for green tea.</div><script> const button = document.querySelector("button"); const answer = document.getElementById("water"); button.addEventListener("click", () => { answer.hidden = !answer.hidden; button.ariaExpanded = String(!answer.hidden); });</script>The button. Lines 1, 2, and 8 change. Before the fix, Chrome's tree showed the button with no expanded state at all. After it, the button says expanded: true when the answer shows.
The questions sit under the h2 Tea FAQ, but they're at level 2 too. Fix it. What does the page print then?
<h2>Tea FAQ</h2><tea-details> <span slot="summary">How hot should the water be?</span> <p>About 80 degrees for green tea.</p></tea-details><tea-details> <span slot="summary">How long should it steep?</span> <p>Two minutes for sencha.</p></tea-details><script type="module"> import "./tea-kit/index.js"; const heading = document.querySelector("tea-details").shadowRoot.querySelector('[role="heading"]'); console.log("Level:", heading.ariaLevel);</script><h2>Tea FAQ</h2><tea-details level="3"> <span slot="summary">How hot should the water be?</span> <p>About 80 degrees for green tea.</p></tea-details><tea-details level="3"> <span slot="summary">How long should it steep?</span> <p>Two minutes for sencha.</p></tea-details><script type="module"> import "./tea-kit/index.js"; const heading = document.querySelector("tea-details").shadowRoot.querySelector('[role="heading"]'); console.log("Level:", heading.ariaLevel);</script>Level: 3. Only lines 2 and 6 change. The callback turns the attribute into the heading's aria-level, so the questions sit under Tea FAQ in the outline.
Make Expand all open every question and Collapse all close them, and print each toggle. How many lines does Expand all print?
<button id="expand">Expand all</button> <button id="collapse">Collapse all</button><tea-details open> <span slot="summary">How hot should the water be?</span> <p>About 80 degrees for green tea.</p></tea-details><tea-details> <span slot="summary">How long should it steep?</span> <p>Two minutes for sencha.</p></tea-details><tea-details> <span slot="summary">Can I reuse the leaves?</span> <p>Yes. Oolong brews well two or three times.</p></tea-details><script type="module"> import "./tea-kit/index.js"; const all = [...document.querySelectorAll("tea-details")]; // Open or close every question, and print each toggle.</script><button id="expand">Expand all</button> <button id="collapse">Collapse all</button><tea-details open> <span slot="summary">How hot should the water be?</span> <p>About 80 degrees for green tea.</p></tea-details><tea-details> <span slot="summary">How long should it steep?</span> <p>Two minutes for sencha.</p></tea-details><tea-details> <span slot="summary">Can I reuse the leaves?</span> <p>Yes. Oolong brews well two or three times.</p></tea-details><script type="module"> import "./tea-kit/index.js"; const all = [...document.querySelectorAll("tea-details")]; for (const details of all) details.addEventListener("toggle", (event) => console.log("toggle:", event.newState)); document.getElementById("expand").addEventListener("click", () => { for (const details of all) details.open = true; }); document.getElementById("collapse").addEventListener("click", () => { for (const details of all) details.open = false; });</script>2. Lines 17 to 23 replace the comment. The first question is already open, so the guard returns for it. Only the other two change, and each prints toggle: open. Collapse all then prints toggle: closed three times.
The three questions share name="faq", but tea-details doesn't read it. Make opening one close the others. Click the first question, then the second. What does the page print the second time?
<tea-details name="faq"> <span slot="summary">How hot should the water be?</span> <p>About 80 degrees for green tea.</p></tea-details><tea-details name="faq"> <span slot="summary">How long should it steep?</span> <p>Two minutes for sencha.</p></tea-details><tea-details name="faq"> <span slot="summary">Can I reuse the leaves?</span> <p>Yes. Oolong brews well two or three times.</p></tea-details><script type="module"> import "./tea-kit/index.js"; const question = (details) => details.querySelector('[slot="summary"]').textContent; const print = () => console.log("Open:", [...document.querySelectorAll("tea-details[open]")].map(question).join(", ")); // Close the other tea-details with the same name, then print().</script><tea-details name="faq"> <span slot="summary">How hot should the water be?</span> <p>About 80 degrees for green tea.</p></tea-details><tea-details name="faq"> <span slot="summary">How long should it steep?</span> <p>Two minutes for sencha.</p></tea-details><tea-details name="faq"> <span slot="summary">Can I reuse the leaves?</span> <p>Yes. Oolong brews well two or three times.</p></tea-details><script type="module"> import "./tea-kit/index.js"; const question = (details) => details.querySelector('[slot="summary"]').textContent; const print = () => console.log("Open:", [...document.querySelectorAll("tea-details[open]")].map(question).join(", ")); document.addEventListener("toggle", (event) => { const opened = event.target; if (opened.localName !== "tea-details" || !opened.open) return; for (const other of document.querySelectorAll(`tea-details[name="${opened.getAttribute("name")}"]`)) if (other !== opened) other.open = false; print(); }, true);</script>Open: How long should it steep? Lines 17 to 22 replace the comment. The listener runs in the capture phase, so it hears toggle on its way down. Web Awesome's closeOthersWithSameName() and Chrome's fallback for details do the same.
Check your understanding
For each question, ask what the accessibility tree holds, and how many real changes happen.
Question 1 of 8In the ARIA accordion pattern, what wraps each header's button?
Choose an answer to see the explanation.
Question 2 of 8Which element carries
aria-expandedin an accordion?Choose an answer to see the explanation.
Question 3 of 8Two
<details name="faq">elements each live in a different shadow root. You open one. What happens to the other?Choose an answer to see the explanation.
Question 4 of 8What does Chrome's tree show for
<summary><h3>How hot should the water be?</h3></summary>?Choose an answer to see the explanation.
Question 5 of 8The teammate's faq-item has no guard. Which lines does it print?
Read the code, then predict<faq-item>How hot should the water be?</faq-item> <script> class FaqItem extends HTMLElement { static observedAttributes = ["open"]; #open = false; get open() { return this.#open; } set open(value) { const open = Boolean(value); // No guard on this line. this.#open = open; this.toggleAttribute("open", open); console.log("toggle:", open ? "open" : "closed"); } attributeChangedCallback(name, oldValue, newValue) { this.open = newValue !== null; } } customElements.define("faq-item", FaqItem); const item = document.querySelector("faq-item"); item.open = true; item.setAttribute("open", ""); item.removeAttribute("open"); </script>Choose an answer to see the explanation.
Question 6 of 8Which keys does the APG's accordion pattern list?
Choose an answer to see the explanation.
Question 7 of 8When does the APG say to skip the region role on panels?
Choose an answer to see the explanation.
Question 8 of 8Does a
<details>element firebeforetoggle?Choose an answer to see the explanation.
Key takeaways
- An accordion is a stack of headings, each holding one button that shows or hides its panel.
- The button carries
aria-expandedandaria-controls. A region on the panel is optional. - Use
<details>and<summary>first. A sharednameopens them one at a time. - A name group only holds details in the same tree. Keep them in the page, or slot them in.
- A summary can't be a heading. When each question must be one, build your own element.
- Keep a custom accordion's ids inside one shadow root, and hide closed answers with
hidden="until-found". - Reflect a boolean
openboth ways withtoggleAttribute()and a guard, so each change fires once. - Support Enter, Space, and Tab. Leave the arrow keys to scroll the page.
Remember the one-liner.
Each question is a heading with a button inside, the button says expanded or not, and the arrow keys keep scrolling.
Sources
The facts on this page come from these standards, docs, and posts:
- Accordion pattern, W3C WAI-ARIA Authoring Practices.
- Accordion example, W3C WAI-ARIA Authoring Practices.
- Collapsible Sections, Heydon Pickering, Inclusive Components.
- Accordion, Chrome for Developers, Modern Web Guidance.
- HTML Standard: the details element, WHATWG.
- <details>: multiple named disclosure boxes, MDN.
- HTML Standard: find-in-page and details, WHATWG.
- Accordion research, Open UI Community Group.
- Web Awesome details, closeOthersWithSameName(), Web Awesome 3.15.0.
- <summary>: summaries as headings, MDN.
- ARIA in HTML: summary, W3C.
- HTML Accessibility API Mappings: summary, W3C.
- HTML Standard: the hidden attribute, WHATWG.
- HowTo: Components, howto-accordion, Google Chrome Labs.
- Attribute reflection: boolean reflected attributes, MDN.
- Accordion Pattern: Remove optional arrow, home, and end keys, W3C ARIA Practices, pull request 3434.
- Accordion pattern: blocking problem with the recommendation to use Up and Down arrows, W3C ARIA Practices, issue 3406.
- browser-compat-data, MDN.
Coming next: Dialogs and popovers in components, in Accessible components. It puts dialogs and popovers inside components, without trapping or losing focus.