Accessible Dialog and Tabs, Step by Step
Build an account page whose tab switcher, delete-confirmation dialog, combobox and menu button follow the WAI-ARIA Authoring Practices, then verify every interaction with key presses and the accessibility tree.
Contentsand lesson path
On this page
- Why it matters
- Step 1: wire the tab markup
- Step 2: move focus with the arrow keys
- Step 3: the confirmation dialog
- Step 4: verify with keys and the tree
- Step 5: a combobox, where focus stays in the input
- Step 6: a menu button, and when not to use one
- Ways this build goes wrong
- Check your understanding
- Apply it
- Review prompt
Lessons of Web Accessibility
- Who Accessibility Serves and How WCAG 2.2 Is Organized Concept · 20 min
- Keyboard Access and Focus Management Worked example · 25 min
- ARIA: When, Why and How Little Concept · 20 min
- Accessible Dialog and Tabs, Step by Step Worked example · 30 min
- Lab: Audit with axe, a Keyboard and a Screen Reader Lab · 30 min
- Check: Triage Accessibility Defects Knowledge check · 8 questions
What you will learn
- Implement keyboard-operable custom widgets (dialog, menu, tabs, combobox) following the WAI-ARIA Authoring Practices, with visible focus and correct focus management.
- Apply ARIA roles, states, properties and live regions only where native HTML falls short, and verify the result in the accessibility tree.
Prerequisites: Semantic HTML
01. Why it matters
Custom widgets such as tabs, dialogs, comboboxes and menus tend to break in the same way: the markup looks plausible, but focus ends up somewhere no one planned. The WAI-ARIA Authoring Practices Guide (APG) publishes a pattern for each — the roles, the states and the exact key presses a keyboard user expects. This lesson builds tabs and a dialog on one small account page, then a combobox and a menu button, using ARIA only where native HTML stops and verifying the result by driving real keys.
The lesson after this one audits a page with automated tools; this one is the manual craft those audits cannot see.
02. Step 1: wire the tab markup
Native HTML has no tab widget, so this is a genuine ARIA case — the third situation in the ARIA lesson. Three roles work together: a tablist container, tab buttons, and tabpanel regions. Each tab names its panel with aria-controls, each panel names itself back with aria-labelledby, and the state lives in aria-selected. The visible tab text doubles as the accessible name, so no extra labelling is needed:
<div role="tablist" aria-label="Account sections">
<button role="tab" id="tab-profile" aria-controls="panel-profile"
aria-selected="true" tabindex="0" type="button">Profile</button>
<button role="tab" id="tab-billing" aria-controls="panel-billing"
aria-selected="false" tabindex="-1" type="button">Billing</button>
<button role="tab" id="tab-teams" aria-controls="panel-teams"
aria-selected="false" tabindex="-1" type="button">Teams</button>
</div>
<div role="tabpanel" id="panel-profile" aria-labelledby="tab-profile"
tabindex="0">
<p><a href="/profile.html">Edit profile</a></p>
</div>
<div role="tabpanel" id="panel-billing" aria-labelledby="tab-billing"
tabindex="0" hidden>
<button type="button" id="open-delete">Delete account…</button>
</div>
<div role="tabpanel" id="panel-teams" aria-labelledby="tab-teams"
tabindex="0" hidden>
<p>No teams yet.</p>
</div>Two tabindex choices carry the pattern. Every panel has tabindex="0" so keyboard users can reach panel content — including scrolling a panel that overflows — with Tab. The tabs use what is called a roving tabindex: exactly one tab carries tabindex="0", the others -1, so the whole tablist is a single stop in the page's Tab order.
03. Step 2: move focus with the arrow keys
The APG tabs pattern expects Left and Right arrows to move between horizontal tabs (Up and Down for vertical tablists), wrapping from first to last, optional Home and End to jump to ends, and activation to follow focus. A select() function does all of it — states, hidden panels, tabIndex, and focus, in that order:
const tabs = [...document.querySelectorAll('[role="tab"]')];
const panels = tabs.map((tab) =>
document.getElementById(tab.getAttribute('aria-controls')));
function select(index) {
tabs.forEach((tab, i) => {
const active = index === i;
tab.setAttribute('aria-selected', String(active));
tab.tabIndex = active ? 0 : -1;
panels[i].hidden = !active;
});
tabs[index].focus();
}
tabs.forEach((tab, index) => {
tab.addEventListener('click', () => select(index));
tab.addEventListener('keydown', (event) => {
if (event.key === 'ArrowRight') select((index + 1) % tabs.length);
if (event.key === 'ArrowLeft') {
select((index - 1 + tabs.length) % tabs.length);
}
if (event.key === 'Home') select(0);
if (event.key === 'End') select(tabs.length - 1);
});
});Because activation follows focus, one arrow press updates the selection, the panel and the roving stop at once, and the modulo arithmetic gives the wrapping the APG asks for.
This is called automatic activation, and it is the right default whenever showing a panel is cheap. The APG also describes manual activation: focus moves with the arrows, and the user confirms with Enter or Space. Choose manual when switching fires a network request or discards unsaved input. Either way, only where you call select() changes.
04. Step 3: the confirmation dialog
The Billing panel holds the destructive action, and destructive actions deserve a modal dialog. The native <dialog> element from the keyboard lesson supplies the inert background (so focus cannot reach the page behind), the Escape handling and focus return; ARIA supplies what the browser cannot guess — the name and the description the dialog is announced with:
<dialog id="confirm" aria-labelledby="confirm-title"
aria-describedby="confirm-desc">
<h2 id="confirm-title">Delete this account?</h2>
<p id="confirm-desc">All projects and invoices are removed. This
cannot be undone.</p>
<button type="button" id="cancel">Cancel</button>
<button type="button" id="confirm-delete">Delete account</button>
</dialog>When the dialog opens, a screen reader announces name, then description: "Delete this account? All projects and invoices are removed…". aria-labelledby names it after the question, aria-describedby attaches the warning. Opening it is showModal() from the Delete button's click handler; closing is .close() from both buttons.
One decision is yours to make deliberately: where focus lands first. The browser's default is the dialog's first focusable control, here Cancel. That is usually what you want for a destructive prompt — the APG suggests starting on the least dangerous control, and if your layout makes the first control risky instead, add the autofocus attribute to the safe button and the browser will start there. What you should not do is script your own focus placement on top of the modal element; you would be re-implementing behaviour the browser already owns.
const dialog = document.getElementById('confirm');
document.getElementById('open-delete').addEventListener('click', () => {
dialog.showModal();
});
for (const id of ['cancel', 'confirm-delete']) {
document.getElementById(id).addEventListener('click', () => dialog.close());
}05. Step 4: verify with keys and the tree
Now prove the pattern the way a keyboard user experiences it — Tab once, arrows, Tab again, Enter, Escape — printing the focused element at every step. The scripts use playwright 1.64.1, installed as in the ARIA lesson. First put the code from steps 1 to 3 into one page, where the comments mark:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Account</title>
</head>
<body>
<main>
<!-- step 1: the tablist and the three panels -->
<!-- step 3: the <dialog> -->
</main>
<script>
// step 2: the select() code, then step 3: the dialog handlers
</script>
</body>
</html>import { chromium } from 'playwright';
import { pathToFileURL } from 'node:url';
const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto(pathToFileURL('account.html').href);
async function describe(page) {
return page.evaluate(() => {
const el = document.activeElement;
const text = el.textContent.trim().slice(0, 30);
const selected = el.getAttribute('aria-selected');
return `<${el.tagName.toLowerCase()}> ${text}`
+ (selected ? `, aria-selected=${selected}` : '');
});
}
const steps = [
['Tab 1 (tablist)', 'Tab'],
['ArrowRight (to Billing)', 'ArrowRight'],
['Tab (into panel)', 'Tab'],
['Tab (to button)', 'Tab'],
['Enter (opens dialog)', 'Enter'],
['Tab (inside dialog)', 'Tab'],
['Escape', 'Escape'],
];
for (const [label, key] of steps) {
await page.keyboard.press(key);
console.log(label.padEnd(22), '->', await describe(page));
}
console.log(await page.locator('[role="tablist"]').ariaSnapshot());
await browser.close();Tab 1 (tablist) -> <button> Profile, aria-selected=true
ArrowRight (to Billing) -> <button> Billing, aria-selected=true
Tab (into panel) -> <div> Delete account…
Tab (to button) -> <button> Delete account…
Enter (opens dialog) -> <button> Cancel
Tab (inside dialog) -> <button> Delete account
Escape -> <button> Delete account…
- tablist "Account sections":
- tab "Profile"
- tab "Billing" [selected]
- tab "Teams"Every APG promise is visible in that log: one Tab stop for the whole tablist, arrows moving the selection, a panel stop before its controls (we give every panel tabindex="0" so scrollable content is reachable; the APG recommends it only when a panel has no focusable element or does not start with one), focus entering the dialog on open and returning to the opener on Escape. The last four lines are the aria snapshot of the tablist; it confirms what assistive technology sees — three tabs, one selected, the group named.
06. Step 5: a combobox, where focus stays in the input
Billing also needs a country field, and that is a combobox: a text input with a popup list of suggestions. HTML's <datalist> is similar, but the browser controls how its list looks and behaves; when you build your own, follow the APG combobox pattern. The markup for it, and for the menu button in step 6, lives in a small widgets.html page:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Combobox and menu button</title>
<style>
[aria-selected="true"] { outline: 2px solid; }
[role="menuitem"]:focus { outline: 2px solid; }
</style>
</head>
<body>
<main>
<label for="country">Billing country</label>
<input id="country" type="text" role="combobox" autocomplete="off"
aria-autocomplete="list" aria-expanded="false"
aria-controls="country-list">
<ul id="country-list" role="listbox" aria-label="Countries" hidden>
<li role="option" id="opt-ca" aria-selected="false">Canada</li>
<li role="option" id="opt-fr" aria-selected="false">France</li>
<li role="option" id="opt-in" aria-selected="false">India</li>
<li role="option" id="opt-ie" aria-selected="false">Ireland</li>
</ul>
<button type="button" id="actions" aria-haspopup="menu"
aria-expanded="false" aria-controls="actions-menu">Actions</button>
<ul id="actions-menu" role="menu" aria-labelledby="actions" hidden>
<li role="menuitem" tabindex="-1">Rename</li>
<li role="menuitem" tabindex="-1">Duplicate</li>
<li role="menuitem" tabindex="-1">Archive</li>
</ul>
</main>
<script src="combobox.js"></script>
<script src="menu-button.js"></script>
</body>
</html>The input keeps its native <label> and gets role="combobox". aria-expanded says whether the list is showing, aria-controls points at the role="listbox" popup, and aria-autocomplete="list" says the suggestions follow what the user types. The key decision is focus. DOM focus, the element that receives key presses, stays in the input the whole time, so the user can keep typing. Arrow keys move only a highlight, and aria-activedescendant on the input names the highlighted option's id, which is how a screen reader learns which option to announce. aria-selected="true" marks the same option:
const input = document.getElementById('country');
const list = document.getElementById('country-list');
const options = [...list.querySelectorAll('[role="option"]')];
let active = -1;
const shown = () => options.filter((option) => !option.hidden);
function highlight(index) {
active = index;
const current = shown()[index];
options.forEach((option) => {
option.setAttribute('aria-selected', String(option === current));
});
if (current) input.setAttribute('aria-activedescendant', current.id);
else input.removeAttribute('aria-activedescendant');
}
function setOpen(open) {
list.hidden = !open;
input.setAttribute('aria-expanded', String(open));
if (!open) highlight(-1);
}
function choose(option) {
input.value = option.textContent;
setOpen(false);
}Every change goes through highlight() and setOpen(), the same single-writer idea as select() in the tabs. The handlers then map the APG keys onto them: typing filters the list, ArrowDown and ArrowUp open it and move the highlight, stopping at the first and last option, Enter accepts the highlighted option, and Escape closes the list but keeps the typed text:
input.addEventListener('input', () => {
const typed = input.value.trim().toLowerCase();
options.forEach((option) => {
option.hidden = !option.textContent.toLowerCase().startsWith(typed);
});
setOpen(shown().length > 0);
highlight(-1);
});
input.addEventListener('keydown', (event) => {
const count = shown().length;
if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
event.preventDefault(); // keep the text cursor where it is
if (count === 0) return;
setOpen(true);
const step = event.key === 'ArrowDown' ? 1 : -1;
if (active === -1) highlight(step === 1 ? 0 : count - 1);
else highlight(Math.min(Math.max(active + step, 0), count - 1));
} else if (event.key === 'Enter' && active >= 0) {
event.preventDefault();
choose(shown()[active]);
} else if (event.key === 'Escape') {
setOpen(false);
}
});
options.forEach((option) => {
// mousedown, not click: it fires before the input loses focus
option.addEventListener('mousedown', (event) => {
event.preventDefault();
choose(option);
});
});
input.addEventListener('blur', () => setOpen(false));08. Ways this build goes wrong
09. Check your understanding
10. Apply it
Port this build into your component library, then extend it along the skill's practice task: add a fourth tab and make Home and End work, wire the same dialog pattern to your most destructive action, and add an aria-live status region that announces "Settings saved" from a container that already exists. If you work in React, the components skill covers the state handling — keep select() as the single writer of aria-selected, tabIndex and hidden, and drive it from one piece of state. Re-run the key-press script from this lesson after each change.
11. Review prompt
Without looking back: list the three roles of the tabs pattern and the attributes each carries. Explain the roving tabindex — what value each tab holds, what the arrows do, and why the panel is also a Tab stop. Say what showModal() provides versus what aria-labelledby and aria-describedby add, and name the two things the expected keyboard log proves about focus. Then explain where DOM focus sits in a combobox and in a menu button, and why a disclosure often beats role="menu" for site navigation.
References
- WAI-ARIA Authoring Practices Guide: Tabs pattern
- WAI-ARIA Authoring Practices Guide: Dialog (Modal) pattern
- WAI-ARIA Authoring Practices Guide: Combobox pattern
- WAI-ARIA Authoring Practices Guide: Menu Button pattern
- WAI-ARIA Authoring Practices Guide: Disclosure (Show/Hide) pattern
- MDN Web Docs: The dialog element
- MDN Web Docs: ARIA roles
- MDN Web Docs: tabindex
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.