The previous lesson in this module covered writing render functions that turn data into markup, and this one closes the module by looking at how to make that markup easy for everybody to use. Accessibility is mostly a result of how you build the page, and not a separate feature that you bolt on at the end. Focus that lands in the right place, controls that announce what they do, and errors that are read out loud instead of only turning red all come down to a handful of attributes and a few habits. This lesson covers the ones that matter most for JavaScript developers.
Where should the keyboard focus go after you change the page?
Two rules cover most cases. When you open something that takes over the screen, move the focus into it. When you close it again, put the focus back on the control that opened it, so that the person is returned to where they were. Forget the second half and a keyboard user who closes a dialog gets dumped back at the top of the page.
<header><p>Tutorsbot</p></header>
<nav aria-label="Sections"><a href="#one">One</a></nav>
<main id="main">
<h1>Settings</h1>
<button id="open-dialog" aria-haspopup="dialog" aria-controls="dialog">Open settings</button>
<div id="dialog" hidden role="dialog" aria-modal="true" aria-labelledby="dialog-title">
<h2 id="dialog-title">Settings</h2>
<input id="nickname" type="text">
<button id="close-dialog">Close</button>
</div>
<p id="status" role="status" aria-live="polite"></p>
<button id="toggle" aria-expanded="false" aria-controls="details">More</button>
<div id="details" hidden>Extra information</div>
<form id="signup">
<label for="email">Email address</label>
<input id="email" type="email" aria-describedby="email-error">
<p id="email-error"></p>
</form>
<button id="icon-only" aria-label="Save to favourites">
<span class="glyph" aria-hidden="true">*</span>
</button>
</main>
const openBtn = document.querySelector("#open-dialog");
const closeBtn = document.querySelector("#close-dialog");
const dialog = document.querySelector("#dialog");
const firstField = document.querySelector("#nickname");
let lastFocused = null;
function openDialog() {
lastFocused = document.activeElement;
dialog.hidden = false;
firstField.focus();
}
function closeDialog() {
dialog.hidden = true;
if (lastFocused) {
lastFocused.focus();
}
}
openBtn.addEventListener("click", openDialog);
closeBtn.addEventListener("click", closeDialog);
openBtn.focus(); // clicking a button gives it the focus
openBtn.click();
console.log(dialog.hidden); // false
console.log(document.activeElement.id); // "nickname"
closeBtn.click();
console.log(dialog.hidden); // true
console.log(document.activeElement.id); // "open-dialog"
The lastFocused variable is the part that people leave out. Saving the element that was focused before the change, instead of hard-coding a place to return to, means that the same dialog works correctly when it is opened from several different places.
How do you announce a change that happened without a page reload?
When the page changes under a screen reader user, such as when a search returns results, an item is saved, or an error appears, nothing happens visually to draw their attention and they may never notice. A live region fixes that problem. It is an ordinary element with role="status" and aria-live="polite" that you write messages into.
Two details matter here. The region has to exist in the page before you write to it, because inserting a live region and filling it in at the same moment often announces nothing at all. And the choice between polite and assertive is the difference between a message that waits for a gap in the speech and one that cuts in immediately. Use polite for almost everything, and keep assertive for the few things that genuinely cannot wait.
const status = document.querySelector("#status");
// The region was already in the page, so writing to it is announced.
status.textContent = "3 results found";
console.log(status.textContent); // "3 results found"
console.log(status.getAttribute("role")); // "status"
console.log(status.getAttribute("aria-live")); // "polite"
// Assertive cuts in immediately, so use it sparingly.
status.setAttribute("aria-live", "assertive");
status.textContent = "Your session expired, please sign in again";
console.log(status.getAttribute("aria-live")); // "assertive"
Because the message is announced when it changes, writing the same text twice in a row announces nothing the second time. If a count goes from 3 to 3 and back to 3, vary the wording or clear the region first, or the person misses the update completely.
How does a form control get its accessible name?
The accessible name is the label that a screen reader announces for a control. There are three ways to supply it, and they are not interchangeable. A <label for="email"> element gives a visible label and it is the best option, because people who can see the page and people who cannot get exactly the same thing. aria-label sets the name from an attribute and is the fallback for when there is no room for a visible label. aria-labelledby points at the text of another element, which is useful when a heading already names a group.
What it is often confused with is aria-describedby, which supplies the description and not the name. A field can have a name from its label and a description that points at a hint or an error message, and it is common to need both of them at once.
const email = document.querySelector("#email");
const error = document.querySelector("#email-error");
// The description points at the error message, not at the name.
console.log(email.getAttribute("aria-describedby")); // "email-error"
// aria-invalid tells assistive technology that the field currently holds bad data.
email.setAttribute("aria-invalid", "true");
error.textContent = "Enter a valid email address";
console.log(email.getAttribute("aria-invalid")); // "true"
email.setAttribute("aria-invalid", "false");
error.textContent = "";
console.log(email.getAttribute("aria-invalid")); // "false"
The visible error message and the state of the field have to be changed together, exactly as the last two lines show. A field that is marked invalid but has no message explains nothing, and a message beside a field that is not marked invalid is easy to miss.
How do you build a button that expands a panel correctly?
A show-and-hide control is the most common piece of interactive JavaScript on the web, and it has a well-established pattern. The trigger is a real <button> with aria-expanded set to "false" or "true", and with aria-controls naming the panel that it toggles. The panel is hidden with the hidden attribute and not with a CSS class that only hides it visually.
const toggle = document.querySelector("#toggle");
const panel = document.querySelector("#details");
toggle.addEventListener("click", function () {
const expanded = toggle.getAttribute("aria-expanded") === "true";
toggle.setAttribute("aria-expanded", String(!expanded));
panel.hidden = expanded;
});
console.log(toggle.getAttribute("aria-expanded")); // "false"
toggle.click();
console.log(toggle.getAttribute("aria-expanded")); // "true"
console.log(panel.hidden); // false
Keeping aria-expanded and the hidden attribute in step is the whole job. Get it wrong and a screen reader announces "collapsed" while the panel is wide open, or it says the opposite. Because the two live in different places, it is worth setting them together in one place in your code rather than in two separate places.
Why do headings and landmarks matter as much as ARIA?
Before you add a single ARIA attribute, make sure that the document structure is right. Screen reader users navigate long pages by heading, by landmark, and by list. A page with a sensible heading order and one <main> region is far easier to navigate than a page that has tried to compensate for bad structure with a pile of roles.
Landmarks are the regions that a page is divided into, such as <header>, <nav>, <main>, <footer>, and <aside>. When a page has more than one of the same kind, give each one a label so that they can be told apart, with <nav aria-label="Sections"> rather than two unlabelled navigation regions.
// Landmarks give a screen reader a way to jump between regions.
const main = document.querySelector("main");
const nav = document.querySelector("nav");
console.log(main.id); // "main"
console.log(nav.getAttribute("aria-label")); // "Sections"
console.log(document.querySelectorAll("h1").length); // 1
console.log(document.querySelector("h2").textContent); // "Settings"
The single <h1> matters because it is the title of the page, and the headings below it should step down one level at a time. Skipping from <h1> straight to <h4> breaks the outline that heading navigation depends on, and no ARIA attribute can repair it.
What makes a custom control usable with the keyboard?
The most reliable way to make something operable by keyboard is not to make it operable by keyboard at all. A real <button> is focusable, it responds to Enter and Space, it fires a click event, it is announced as a button, and it takes part in the form. A <div> with a click listener on it does none of those things.
When you genuinely need something that is not a button, such as a custom listbox, a draggable handle, or a clickable card, you have to supply the missing behaviour yourself. Make it focusable with tabindex="0", give it a role so that it is announced correctly, and handle Enter and Space yourself.
const fake = document.createElement("div");
fake.id = "fake-button";
fake.tabIndex = 0;
fake.setAttribute("role", "button");
fake.textContent = "Press me";
document.body.append(fake);
fake.focus();
console.log(document.activeElement.id); // "fake-button", it is reachable now
// But Enter and Space still have to be handled by hand.
fake.addEventListener("keydown", function (event) {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
console.log("activated");
}
});
fake.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
There is a good reason why the built-in <button> is preferable, because everything on that list is easy to forget and each omission stays invisible until somebody tries to use the page without a mouse. Icons need help as well. An icon-only button has no visible text, so give it an aria-label, and mark the decorative shape itself with aria-hidden="true" so that it is not announced twice.
const iconButton = document.querySelector("#icon-only");
const glyph = iconButton.querySelector(".glyph");
console.log(iconButton.getAttribute("aria-label")); // "Save to favourites"
console.log(glyph.getAttribute("aria-hidden")); // "true"
console.log(glyph.textContent); // "*", visible but not announced
The DOM accessibility checklist
- Move the focus into an overlay when it opens, and back to the trigger when it closes.
- Put a live region in the page before you write to it, and use
role="status"for polite announcements. - Give every control a name: a
<label for>first, andaria-labeloraria-labelledbyonly if you must. - Keep
aria-invalidand the visible error message in step with each other. - Keep
aria-expandedand thehiddenattribute in step with each other. - Use landmarks and a sensible heading order before you reach for ARIA.
- Prefer a real
<button>over a clickable<div>, and never remove the focus outline.
Try it yourself: turn off your mouse and open a page that you built. Tab through every control and note where the focus goes and whether you can always see it. Open a modal if there is one and check whether the focus moves inside it. Submit a form with an error and see whether a screen reader would have any way of knowing which field is wrong. Then open the inspector, find the input, and add aria-describedby that points at an error paragraph that already exists in your markup.