Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Worked example · 30 min · revision 3

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

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:

HTML · account.html (markup only)
<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:

JavaScript · account.html (script)
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:

HTML · account.html
<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.

JavaScript · account.html (script, after the step 2 code)
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:

HTML · account.html (page shell)
<!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>
JavaScript · keyboard-account.mjs
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();
Expected output
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:

HTML · widgets.html
<!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:

JavaScript · combobox.js (state)
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:

JavaScript · combobox.js (keys and mouse)
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));

07. Step 6: a menu button, and when not to use one

A menu button opens a short list of actions, such as Rename, Duplicate and Archive. Its markup is in widgets.html above: a native <button> with aria-haspopup="menu" and aria-expanded, a role="menu" list, and role="menuitem" items with tabindex="-1". Unlike the combobox, DOM focus moves into the menu. Enter, Space or ArrowDown open it on the first item, ArrowUp on the last; arrows and Home and End move between items; Escape closes it and returns focus to the button; Tab closes it and moves on:

JavaScript · menu-button.js
const button = document.getElementById('actions');
const menu = document.getElementById('actions-menu');
const items = [...menu.querySelectorAll('[role="menuitem"]')];

function openMenu(index) {
  menu.hidden = false;
  button.setAttribute('aria-expanded', 'true');
  items[index].focus();
}
function closeMenu() {
  menu.hidden = true;
  button.setAttribute('aria-expanded', 'false');
  button.focus();
}

button.addEventListener('click', () => {
  if (menu.hidden) openMenu(0);
  else closeMenu();
});
button.addEventListener('keydown', (event) => {
  if (event.key === 'ArrowDown') { event.preventDefault(); openMenu(0); }
  if (event.key === 'ArrowUp') { event.preventDefault(); openMenu(items.length - 1); }
});
menu.addEventListener('keydown', (event) => {
  const index = items.indexOf(document.activeElement);
  const next = { ArrowDown: index + 1, ArrowUp: index - 1, Home: 0,
    End: items.length - 1 }[event.key];
  if (next !== undefined) {
    event.preventDefault();
    items[(next + items.length) % items.length].focus();
  } else if (event.key === 'Escape') {
    closeMenu();
  } else if (event.key === 'Tab') {
    menu.hidden = true; // let Tab move on, but close the menu behind it
    button.setAttribute('aria-expanded', 'false');
  } else if (event.key === 'Enter' || event.key === ' ') {
    event.preventDefault();
    console.log(`menu action: ${document.activeElement.textContent}`);
    closeMenu();
  }
});

Use role="menu" for actions like these, not for a site's navigation links. It promises application-style keys: items are not Tab stops, so a user who expects to Tab through links meets arrow keys instead. The APG's disclosure navigation example explains why it avoids the menu role: typical site navigation does not need the complex keyboard behaviour assistive technology expects from a menu. It uses the disclosure pattern instead: a button with aria-expanded that shows and hides an ordinary list of links, which stay in the Tab order.

Now drive both widgets with real keys, as in step 4:

JavaScript · keys.mjs
import { chromium } from 'playwright';
import { pathToFileURL } from 'node:url';

const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto(pathToFileURL('widgets.html').href);

const describe = () =>
  page.evaluate(() => {
    const el = document.activeElement;
    const name = el.id ? `#${el.id}` : el.textContent.trim();
    const expanded = el.getAttribute('aria-expanded');
    const activeId = el.getAttribute('aria-activedescendant');
    const option = activeId ? document.getElementById(activeId).textContent : '-';
    const parts = [`focus ${el.tagName.toLowerCase()} ${name}`];
    if (el.id === 'country') {
      parts.push(`value "${el.value}"`, `expanded ${expanded}`, `active ${option}`);
    } else if (expanded) {
      parts.push(`expanded ${expanded}`);
    }
    return parts.join(', ');
  });

const steps = [
  ['Tab', 'Tab'],
  ['ArrowDown', 'ArrowDown'],
  ['ArrowDown', 'ArrowDown'],
  ['ArrowUp', 'ArrowUp'],
  ['Enter', 'Enter'],
  ['fill "i"', null],
  ['ArrowDown', 'ArrowDown'],
  ['Escape', 'Escape'],
  ['Tab', 'Tab'],
  ['Enter (menu)', 'Enter'],
  ['ArrowDown', 'ArrowDown'],
  ['Escape', 'Escape'],
];
for (const [label, key] of steps) {
  if (key) await page.keyboard.press(key);
  else await page.locator('#country').fill('i');
  console.log(label.padEnd(13), '->', await describe());
}
await page.locator('#country').focus();
await page.keyboard.press('ArrowDown');
console.log(await page.locator('main').ariaSnapshot());
await browser.close();
Expected output
Tab           -> focus input #country, value "", expanded false, active -
ArrowDown     -> focus input #country, value "", expanded true, active Canada
ArrowDown     -> focus input #country, value "", expanded true, active France
ArrowUp       -> focus input #country, value "", expanded true, active Canada
Enter         -> focus input #country, value "Canada", expanded false, active -
fill "i"      -> focus input #country, value "i", expanded true, active -
ArrowDown     -> focus input #country, value "i", expanded true, active India
Escape        -> focus input #country, value "i", expanded false, active -
Tab           -> focus button #actions, expanded false
Enter (menu)  -> focus li Rename
ArrowDown     -> focus li Duplicate
Escape        -> focus button #actions, expanded false
- main:
  - text: Billing country
  - combobox "Billing country" [expanded]: i
  - listbox "Countries":
    - option "India" [selected]
    - option "Ireland"
  - button "Actions"

Read the combobox lines first: focus never leaves #country, yet the active option walks Canada, France, Canada, Enter writes Canada into the value, and Escape closes the list without throwing away the typed i. The snapshot shows what assistive technology is given: an expanded combobox named Billing country, and India as the selected option. The menu lines show the opposite design: focus moves onto Rename and Duplicate, and Escape hands it back to #actions with aria-expanded false again.

08. Ways this build goes wrong

09. Check your understanding

Practice check · 3 questions

Widget wiring

Three choices from the build.

Q1. What do aria-labelledby and aria-describedby on the <dialog> change?
Q2. After switching tabs in a copy of this code, pressing Tab lands on a tab that was not selected. Which defect is the likely cause?
Q3. In a copy of the combobox, ArrowDown visibly highlights France, but a screen reader keeps announcing only the text field, which still has focus. What is the likely defect?
Practice only: not graded, not saved, not evidence.

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

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check