15. Accessibility Engineering
“A div with an onClick is a button the way a painting of a door is a door.”
The story: the second building
Section titled “The story: the second building”Every web page you build is actually two buildings. One is the building everybody sees: colours, layout, motion, the glass and the lenses. The other is a building made only of signs — “Button: Save essay,” “Heading level 2: Monsoon,” “Dialog: Share, 3 options,” “List, 12 items.” Screen readers, voice control, switch devices and some browser features never see the first building at all. They walk through the second one, sign by sign.
The browser constructs this second building automatically from your HTML. Use a <button>, and the sign says “button,” it’s reachable by Tab, it activates with Enter and Space. Use <div class="btn" onClick>, and the browser puts up… nothing useful. A blank wall where a door should be. You’ve built a beautiful entrance that a screen-reader user, a keyboard user, or a voice-control user can’t find or open.
You already know accessibility as a design discipline — contrast, hierarchy, affordances. This chapter is about the engineering: how the second building is built, how to inspect it, and how to make custom components — modals, comboboxes, canvases — that have real doors.
The accessibility tree
Section titled “The accessibility tree”The browser builds an accessibility tree in parallel with the DOM (and from it, plus CSS). Each node has:
- a role — button, link, heading, textbox, dialog, list, img…
- a name — what it’s called (“Save essay”).
- a description (optional, extra context).
- states and properties — expanded/collapsed, checked, disabled, selected, level (for headings), value.
The platform exposes this tree to assistive technologies through OS accessibility APIs. A screen reader like VoiceOver, TalkBack or NVDA reads the tree — not your pixels.
Not every DOM node becomes an accessibility node. Purely presentational <div>s are often pruned; display: none and visibility: hidden content is removed; aria-hidden="true" removes a subtree. And CSS can change semantics in surprising ways: in some browsers, display: contents or display: grid on a table or list has historically stripped its table/list semantics.
See it yourself: in Chrome DevTools’ Elements panel, open the Accessibility pane for the selected element (role, name, computed properties), or enable the full-page accessibility tree view to browse the tree instead of the DOM. Firefox has an excellent Accessibility Inspector too.
Semantics first, then ARIA
Section titled “Semantics first, then ARIA”HTML elements carry built-in semantics and behaviour:
<button>— role button, focusable, Enter/Space activate it,disabledworks, it submits forms if inside one (settype="button"when it shouldn’t).<a href>— role link, focusable, Enter activates, middle-click/long-press opens in new tab, shows the URL.<input>,<select>,<textarea>,<label>— form semantics, labels clickable, autofill and mobile keyboards.<nav>,<main>,<header>,<footer>,<aside>— landmarks that screen-reader users jump between.<h1>–<h6>— headings, the most-used navigation mechanism for screen-reader users (they skim by headings the way you skim visually).<ul>/<ol>/<li>,<table>with<th>— structure that’s announced (“list, 12 items”).<dialog>— modal semantics and inert background (Chapter 14).
ARIA (Accessible Rich Internet Applications) is a set of attributes that modify the accessibility tree: role, aria-label, aria-expanded, aria-controls, aria-live, and many more. ARIA changes only semantics, never behaviour. role="button" on a div makes a screen reader announce “button,” but the div still isn’t focusable and still doesn’t respond to Enter or Space — you must add tabindex="0" and key handlers yourself, and you’ll probably get some detail wrong.
Hence the first rule of ARIA: if a native HTML element or attribute gives you the semantics and behaviour you need, use it instead of re-purposing an element and adding ARIA. The corollary heard in accessibility circles: no ARIA is better than bad ARIA. Surveys of real websites consistently find pages with ARIA have more accessibility errors on average than pages without, because ARIA is easy to misuse — a wrong role, a stale aria-expanded, aria-hidden on something focusable.
Accessible names
Section titled “Accessible names”Every interactive element needs a name — what assistive tech announces. The browser computes it by an algorithm, in roughly this priority:
aria-labelledby(points at other elements’ text),aria-label(a string),- native labelling (
<label for>,<caption>,<legend>,alton images), - the element’s text content (for buttons, links, headings),
title(last resort; unreliable).
Common failures: icon-only buttons with no name (“button” — which button?), images with missing or useless alt (alt="image", alt="DSC_0042.jpg"), inputs with placeholder text but no label (placeholders vanish when typing and aren’t reliable names), and links named “click here” or “read more” (meaningless out of context — screen-reader users often list all links on a page).
<button aria-label="Close dialog"><svg aria-hidden="true">…</svg></button><img src="monsoon.avif" alt="Rain sheeting across Marine Drive at dusk"><img src="divider.svg" alt=""> <!-- decorative: empty alt, ignored by AT -->The DevTools Accessibility pane shows the computed name and where it came from. Use it.
Focus management in SPAs (route changes!)
Section titled “Focus management in SPAs (route changes!)”In an MPA, every navigation loads a new document: the browser resets focus to the top, and screen readers announce the new page title. In an SPA (Chapter 7), the router swaps content in place and none of that happens. Focus stays on the link the user clicked — which may no longer exist — or falls back to <body>. A screen-reader user hears nothing. Did the click work? They have no idea.
So on every client-side navigation, you must:
- Move focus to something meaningful in the new view — typically the main heading (
<h1 tabindex="-1">so it can receive programmatic focus without entering the tab order) — and do it after the new content has rendered. - Update
document.title. - Optionally, announce the change via a live region (“Monsoon — essay loaded”).
- Restore focus on Back if you restore scroll.
Frameworks increasingly help (some routers announce route changes), but verify with a screen reader; it’s the single most common SPA accessibility failure.
Focus, generally
Section titled “Focus, generally”- Visible focus — never
outline: nonewithout a replacement. Use:focus-visibleto show focus rings for keyboard users without showing them on mouse clicks. - Focus order follows DOM order. If CSS (grid placement,
order, absolute positioning) makes visual order differ from DOM order, keyboard users zig-zag. Keep them aligned. tabindex:0adds an element to the tab order;-1makes it programmatically focusable but not tabbable; positive values create a separate, confusing tab order — don’t use them.- Focus trapping in modals: while a modal is open, Tab must cycle within it; when it closes, focus returns to the element that opened it.
<dialog>withshowModal()and theinertattribute handle most of this natively.
Keyboard interaction patterns
Section titled “Keyboard interaction patterns”Users of keyboards, switches and screen readers expect consistent conventions. The ARIA Authoring Practices Guide documents patterns for common widgets. Highlights:
- Buttons: Enter and Space activate.
- Links: Enter activates.
- Menus, listboxes, radio groups, tabs: one tab stop for the whole widget; arrow keys move between items (the “roving tabindex” technique: the active item has
tabindex="0", the rest-1). Home/End jump to first/last. - Dialogs: Escape closes; focus trapped while open.
- Comboboxes (autocomplete): typing filters; Down Arrow opens/moves through options; Enter selects; Escape closes; the input keeps focus while
aria-activedescendantpoints at the highlighted option. - Disclosure (accordion): a button with
aria-expandedtoggling a region.
Test every custom component with the keyboard alone. If you can’t do it without a mouse, neither can a large number of your users.
Live regions
Section titled “Live regions”Some updates happen without focus moving: “Saved,” “3 results found,” a toast, a form error that appears after submission. Sighted users see them; screen-reader users don’t, unless you announce them. A live region is an element whose content changes are announced:
<div aria-live="polite" class="sr-status"></div> <!-- announced when the user is idle --><div role="alert">Payment failed. Check your card.</div> <!-- assertive: interrupts -->Gotchas: the live region must exist in the DOM before its content changes (inserting a new element that’s already populated often isn’t announced); use polite for most things and assertive/role="alert" sparingly; don’t announce every keystroke.
Motion, contrast, zoom and reflow
Section titled “Motion, contrast, zoom and reflow”You know the design principles; here’s the engineering:
prefers-reduced-motion— users who get motion sickness, vestibular disorders or distraction can ask the OS to reduce motion. Respect it in CSS (@media (prefers-reduced-motion: reduce)) and JS (matchMedia). “Reduce” doesn’t mean “remove all feedback” — replace large movement (parallax, zooms, slides across the screen) with fades or instant changes; keep small state-change cues. Chapter 19 goes deep on doing this well.- Contrast — text needs sufficient contrast against its background (WCAG AA: 4.5:1 for body text, 3:1 for large text and UI component boundaries). Glass and blur effects are a contrast hazard: the background behind translucent panels varies, so contrast must be checked against the worst case, or the panel needs enough opacity to guarantee it. Some users enable
prefers-reduced-transparencyorprefers-contrast: more; honour them where supported. - Zoom and reflow — content must work at 200% zoom and reflow into a single column at a 320 CSS-pixel-wide viewport without horizontal scrolling (except for things like data tables and diagrams that genuinely need two dimensions — which is why this book’s wide figures scroll inside their own container). Use relative units for text; never disable pinch zoom (
user-scalable=no). - Target size — touch targets big enough to hit (WCAG 2.2 sets a minimum of 24×24 CSS px, with exceptions; 44–48 px is a better design target on mobile).
- Forced colours (Windows High Contrast) — custom controls drawn with backgrounds and box-shadows may disappear; use real borders/outlines and test with
forced-colors: active.
Testing
Section titled “Testing”Automated tools catch maybe a third of accessibility issues — the mechanical ones. The rest require humans.
- axe (axe-core, via browser extension, DevTools integrations, or in your test suite and CI with tools like Playwright) — fast, low false positives: missing names, invalid ARIA, contrast, missing labels, duplicate IDs.
- Lighthouse’s accessibility audit — runs a subset of axe checks; a score of 100 means “no automatically detectable issues,” not “accessible.”
- Keyboard-only pass — unplug the mouse (figuratively). Tab through every flow. Is focus visible? Is the order logical? Can you open, use and close every component?
- Real screen readers — the only way to know what users hear:
- VoiceOver on macOS (Cmd+F5) and iOS (Settings → Accessibility). Safari is its best partner.
- TalkBack on Android (with Chrome) — essential for an Indian audience on Android.
- NVDA on Windows (free; with Firefox or Chrome). JAWS is the commercial veteran, still common in enterprise. Learn the basics: navigate by headings, by landmarks, by form controls; list links; activate controls.
Put axe in CI (Chapter 3) so regressions fail builds, and do a manual keyboard + screen-reader pass on every significant new component.
Custom components
Section titled “Custom components”Modals. Use <dialog> + showModal(). Give it a name (aria-labelledby pointing at its heading). Return focus to the trigger on close. If you can’t use <dialog>, you need: role="dialog", aria-modal="true", a name, focus moved in, focus trapped, Escape to close, background made inert, focus returned on close. That’s a lot of places to be wrong — another argument for the native element.
Comboboxes. The hardest common widget. An input with role="combobox", aria-expanded, aria-controls pointing at a role="listbox" popup, options with role="option" and unique IDs, aria-activedescendant on the input pointing at the highlighted option (focus stays in the input), and the keyboard behaviour above. Use a well-tested library or follow the Authoring Practices pattern exactly, and test with two screen readers — they differ.
Canvas and WebGL. A <canvas> is one image to the accessibility tree: no structure, no text, no controls. For anything meaningful drawn in canvas:
- give the canvas an accessible name and description (
role="img"+aria-labelfor a static visualization, or a fallback description inside the<canvas>element); - provide the same information in DOM — a data table for a chart, a text summary, real HTML controls for interactions (a slider in DOM controlling the 3D scene’s rotation);
- keep controls keyboard operable; don’t make the canvas the only way to do something;
- respect
prefers-reduced-motionfor animated scenes; - for maths visualizations (the author’s Three.js maths site): a text explanation of what the visualization shows, labelled axes in DOM, and key values announced via a live region as the user manipulates the scene.
This book’s diagrams follow the same rule: every SVG has a <title> and <desc> that say what it shows.
When it goes wrong
Section titled “When it goes wrong”The custom select that trapped keyboard users. A design system’s custom dropdown, built from divs for styling freedom, opened on click but never received focus, so keyboard users couldn’t choose a value — on the checkout’s “state” field. Conversion from keyboard and screen-reader users dropped to zero for that flow until someone filed a complaint. The fix took one day: a native <select> (now increasingly stylable) for the default, the custom one behind a feature flag until it passed the keyboard pattern.
Legal exposure. Thousands of accessibility lawsuits are filed every year in the United States alone, mostly against e-commerce sites, many over missing alt text, unlabeled forms and keyboard traps. The European Accessibility Act applies accessibility requirements to many digital products and services sold in the EU from mid-2025, and India’s Rights of Persons with Disabilities Act and government guidelines set expectations too. Accessibility is a legal requirement in a growing share of your market, not a nice-to-have.
What you now know
Section titled “What you now know”You can explain how the accessibility tree is derived and inspect it; apply the first rule of ARIA; compute and fix accessible names; manage focus on SPA route changes and in modals; implement standard keyboard patterns; use live regions correctly; handle reduced motion, contrast (including glass), zoom, reflow and target size; test with axe, keyboard and VoiceOver/TalkBack/NVDA; and make modals, comboboxes and canvas/WebGL content accessible.
Self-quiz
Section titled “Self-quiz”1. What does role=“button” on a div give you, and what doesn’t it?
It changes the announced role. It does not add focusability or Enter/Space activation — you must add tabindex and key handlers.
2. What’s the first rule of ARIA?
Use native HTML elements/attributes with the semantics and behaviour you need instead of adding ARIA to other elements.
3. What must happen on an SPA route change for screen-reader users?
Focus moves to meaningful new content (e.g. the h1), the title updates, optionally an announcement.
4. Why might a live region not announce?
It was inserted already populated rather than existing first and then changing; or it’s hidden.
5. How do you make a WebGL scene accessible?
Name/describe the canvas, provide equivalent information and controls in DOM, keyboard operability, and reduced-motion support.
Exercises
Section titled “Exercises”Warm-up 1. Name it. What’s the accessible name of: <button><svg>…</svg></button>? <button aria-label="Close">×</button>? <input placeholder="Email">?
Solution
None (unless the SVG has a title); “Close”; possibly “Email” via placeholder fallback in some browsers, but unreliable — add a label.
Warm-up 2. Spot the bug. <div aria-hidden="true"><button>Buy</button></div>. What’s wrong?
Solution
The button is still focusable by keyboard but hidden from assistive tech — a focusable “ghost.” Use inert instead, or don’t hide it.
Warm-up 3. Alt text. Write alt text for: a hero photo of a chai stall in the rain; a decorative wave divider; a chart of LCP over time.
Solution
“A roadside chai stall under a tarp in heavy rain, steam rising from the kettle”; alt=""; a short summary (“LCP improved from 3.4 s to 2.1 s after the March release”) plus the data in a table nearby.
Lab 4. Lumen’s tree. Open Lumen’s essay page in the full-page accessibility tree view. Fix every unnamed control and every heading-level skip.
Expected outcome
Logical heading outline (one h1, nested h2/h3), all buttons and links named, landmarks for header/nav/main/footer.
Lab 5. Route-change focus. Implement focus management for Lumen’s client-side navigations. Test with VoiceOver or TalkBack.
Expected outcome
After activating an essay link, the screen reader announces the new essay’s heading.
Lab 6. axe in CI. Add an automated accessibility check (axe via Playwright) on Lumen’s main pages to CI. Introduce an unlabeled input and watch it fail.
Hint
Run axe against each page after load and fail on serious/critical violations.
Lab 7. Accessible gallery. Make Lumen’s gallery keyboard-navigable with arrow keys (roving tabindex), and its lightbox a proper modal.
Expected outcome
One tab stop into the gallery; arrows move between photos; Enter opens the dialog; Escape closes and returns focus.
Staff 8. Glass and contrast. Your design system’s glass panels fail contrast over some wallpapers. Propose an engineering solution that preserves the aesthetic.
Model answer
Guarantee contrast with a minimum panel opacity or a subtle scrim behind text; compute contrast against the worst-case backdrop region; honour reduced-transparency/high-contrast preferences with solid fills; add a contrast check to the component’s visual tests.
Staff 9. Definition of done. Write the accessibility section of your team’s definition of done for a new component.
Model answer
Native elements where possible; names for all controls; keyboard pattern per APG; visible focus; reduced motion honoured; axe clean in CI; manual check with one desktop and one mobile screen reader; documented usage notes.