Frontend development · Intermediate · 20 min
Announce errors and notices with a live region
By Padding · Updated 18 Nov 2026
Modern browsers · WAI-ARIA 1.2 · checked in Chromium with Playwright 1.65.1
You will build two Larkfield Clinic banners, a polite "10:30 was just taken" notice and an urgent "could not book" error, that screen readers announce once each, plus a Playwright script that checks them in the accessibility tree.
On this page
A message that appears on screen is not automatically a message a screen reader user hears. Screen readers read what has focus and what the user moves to. When a banner appears above a list of times while the user's focus is on the Continue button, a sighted user notices the colour change. A blind user hears nothing and carries on, unaware that their time has gone.
A live region fixes that. It is an element the browser watches: when its content changes, the browser tells assistive technology, which reads the new text without moving focus. WCAG 2.2 calls these status messages (success criterion 4.1.3) and expects them to be announced.
You will build two messages from the Larkfield Clinic booking app, a fictional community clinic used across these tutorials. On Pick a time, the patient's chosen slot is taken by someone else while they decide: "10:30 was just taken. These times are still free." On Check your booking, the clinic's server refuses the booking: "We could not book this time. Your details are saved." The colours are Larkfield's notice and danger pairs from the high-fidelity designs. Along the way you will meet the three mistakes that make live regions stay silent or talk too much, and finish with an automated check you can run in CI.
Step 1 · Build the Pick a time page with an empty region
Create a folder for the demo and a stylesheet with the Larkfield colour tokens as custom properties:
mkdir -p ~/live-region-demo
cd ~/live-region-demo
cat > style.css <<'CSS'
:root {
--text: #1B1F24;
--text-muted: #5A6270;
--surface: #FFFFFF;
--canvas: #F6F7F8;
--line: #D5D9DF;
--accent: #0F5E5A;
--on-accent: #FFFFFF;
--danger: #B42318;
--danger-tint: #FDECEA;
--notice: #8A5A00;
--notice-tint: #FFF4DC;
}
* { box-sizing: border-box; }
body { margin: 0; background: var(--canvas); color: var(--text); font: 16px/24px system-ui, sans-serif; }
main { max-width: 26rem; margin: 0 auto; padding: 16px; }
h1 { font-size: 28px; line-height: 34px; margin: 0 0 4px; }
.service { margin: 0 0 16px; color: var(--text-muted); font-size: 14px; line-height: 20px; }
fieldset { margin: 0 0 16px; padding: 0; border: 0; }
legend { margin-bottom: 8px; font-size: 14px; font-weight: 600; }
.slots { display: flex; flex-wrap: wrap; gap: 8px; }
.slot { display: flex; align-items: center; gap: 6px; min-height: 48px; padding: 0 12px;
background: var(--surface); border: 1px solid var(--line); border-radius: 8px; }
.slot:has(input:disabled) { color: var(--text-muted); text-decoration: line-through; }
.banner { display: flex; gap: 8px; margin: 0 0 16px; padding: 12px;
border-radius: 8px; font-size: 14px; line-height: 20px; }
.banner svg { flex: none; width: 20px; height: 20px; }
#slots-notice .banner { background: var(--notice-tint); color: var(--notice); }
#booking-error .banner { background: var(--danger-tint); color: var(--danger); }
.primary { width: 100%; min-height: 48px; border: 0; border-radius: 8px;
background: var(--accent); color: var(--on-accent); font: inherit; font-weight: 600; }
CSSNow the Pick a time page. Look for the empty div with role="status" above the time slots. That is the live region. It is in the HTML from the start, and it has no content yet:
cd ~/live-region-demo
cat > pick-a-time.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Pick a time · Larkfield Clinic</title>
<link rel="stylesheet" href="style.css">
<script src="announce.js" defer></script>
<script src="app.js" defer></script>
</head>
<body>
<main>
<h1>Pick a time</h1>
<p class="service">Nurse appointment, 15 min · Tue 9 Dec</p>
<div id="slots-notice" role="status"></div>
<fieldset>
<legend>Morning</legend>
<div class="slots">
<label class="slot"><input type="radio" name="time" value="09:00"> 09:00</label>
<label class="slot"><input type="radio" name="time" value="09:30"> 09:30</label>
<label class="slot"><input type="radio" name="time" value="10:00"> 10:00</label>
<label class="slot"><input type="radio" name="time" value="10:30" checked> 10:30</label>
<label class="slot"><input type="radio" name="time" value="11:00"> 11:00</label>
</div>
</fieldset>
<button type="button" class="primary" id="continue">Continue</button>
</main>
</body>
</html>
HTMLThe 10:30 slot is already selected, as if the patient chose it a minute ago. The two scripts do not exist yet; you write them in a later step.
The region itself carries no styling. Banner styles go on a .banner paragraph that the script will put inside it. An empty div takes up no space, so there is no gap above the slots until a message arrives, and the region never needs hiding.
Check it worked
Open pick-a-time.html in your browser (drag the file into a window, or run open pick-a-time.html on macOS or xdg-open pick-a-time.html on Linux). You see the heading, the service line, five Morning slots with 10:30 selected and a full-width Continue button. Nothing appears between the service line and the slots. The browser console shows two errors for the missing scripts; they go away in step 3.
Step 2 · Choose role="status" or role="alert"
Two roles cover nearly every message you will announce:
role="status"is polite. The screen reader finishes what it is saying, then reads the message. Use it for information that helps but does not stop the person: a time has gone and others are still free, search results have updated, a draft was saved.role="alert"is assertive. The screen reader may interrupt itself to read the message straight away. Use it when something the person tried has failed, or when waiting would cost them something.
Both roles also make the region atomic: when anything inside changes, the whole region is read, not just the changed words. That is why one region holds one message.
The "10:30 was just taken" notice is a status. The patient has not lost anything they cannot get back, and the page offers the next step itself. The "could not book" message is an alert. The patient pressed Book appointment and it failed, so they need to hear that before anything else.
Resist making every message an alert. An interruption trains people to ignore interruptions, and two assertive messages at once can cut each other off. You also do not need aria-live as well as the role. The role already sets it, and adding a different value to the same element gives screen readers two instructions to choose between.
Create the Check your booking page with an alert region above the button:
cd ~/live-region-demo
cat > confirm.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Check your booking · Larkfield Clinic</title>
<link rel="stylesheet" href="style.css">
<script src="announce.js" defer></script>
<script src="app.js" defer></script>
</head>
<body>
<main>
<h1>Check your booking</h1>
<p class="service">Nurse appointment · Tuesday 9 December, 10:30</p>
<div id="booking-error" role="alert"></div>
<button type="button" class="primary" id="confirm">Book appointment</button>
</main>
</body>
</html>
HTMLCheck it worked
Open confirm.html in Chrome or Edge, open DevTools (F12), and in the Elements panel select <div id="booking-error" role="alert">. Open the Accessibility tab next to Styles. The role is shown as alert, and the computed properties include a live region setting of assertive and an atomic setting of true. Do the same for the status region on pick-a-time.html: its live region setting is polite. Firefox shows the same information in its Accessibility panel.
Step 3 · Fill the regions from a script
The helper in announce.js builds a banner and puts it in a region. The alert icon is decorative, so it gets aria-hidden="true"; the words already say what happened, and a screen reader should not read "image" before every message. This first version is deliberately simple, and you will improve it in step 5:
cd ~/live-region-demo
cat > announce.js <<'JS'
const ALERT_ICON =
'<svg viewBox="0 0 20 20" aria-hidden="true" focusable="false">' +
'<circle cx="10" cy="10" r="8.5" fill="none" stroke="currentColor" stroke-width="2"/>' +
'<path d="M10 5.5v5.5M10 14v.5" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>';
function makeBanner(text) {
const p = document.createElement('p');
p.className = 'banner';
p.innerHTML = ALERT_ICON;
p.append(text);
return p;
}
function announce(region, text) {
region.replaceChildren(makeBanner(text));
}
function clearAnnouncement(region) {
region.replaceChildren();
}
JSapp.js holds both pages' behaviour. Two small functions stand in for the clinic's server so you can run everything from files: fetchTakenTimes always reports 10:30 as taken, and sendBooking always fails. The Pick a time code checks for taken times when the patient presses Continue, and every 20 seconds while the page is open, because slots go while people decide. The Check your booking code shows the error when the booking fails and relabels the button "Try again":
cd ~/live-region-demo
cat > app.js <<'JS'
// Stand-ins for the clinic's server. Swap them for fetch() calls in the real app.
function fetchTakenTimes() {
return new Promise((resolve) => setTimeout(() => resolve(['10:30']), 300));
}
function sendBooking() {
// In this demo the server always says no, so you can see the error.
return new Promise((resolve, reject) => setTimeout(() => reject(new Error('busy')), 500));
}
// Pick a time
const slotsNotice = document.getElementById('slots-notice');
let lostTime = null;
async function refreshTimes() {
const taken = await fetchTakenTimes();
for (const input of document.querySelectorAll('input[name="time"]')) {
const isTaken = taken.includes(input.value);
if (isTaken && input.checked) {
input.checked = false;
lostTime = input.value;
}
input.disabled = isTaken;
}
if (lostTime) {
announce(slotsNotice, `${lostTime} was just taken. These times are still free.`);
}
}
if (slotsNotice) {
document.querySelectorAll('input[name="time"]').forEach((input) => {
input.addEventListener('change', () => {
lostTime = null;
clearAnnouncement(slotsNotice);
});
});
document.getElementById('continue').addEventListener('click', async () => {
await refreshTimes();
if (document.querySelector('input[name="time"]:checked')) {
location.href = 'confirm.html';
}
});
setInterval(refreshTimes, 20000);
}
// Check your booking
const bookingError = document.getElementById('booking-error');
let sending = false;
if (bookingError) {
const button = document.getElementById('confirm');
button.addEventListener('click', async () => {
if (sending) return;
sending = true;
try {
await sendBooking();
clearAnnouncement(bookingError);
} catch {
announce(bookingError, 'We could not book this time. Your details are saved.', { repeat: true });
button.textContent = 'Try again';
} finally {
sending = false;
}
});
}
JSrefreshTimes works from state. Every time it runs, it works out which message should show and calls announce with it. That keeps the screen honest, because the notice can never fall out of step with the slots, but it means announce is called with the same words on every poll. You deal with that in step 5.
The { repeat: true } option on the error does nothing yet. The final helper uses it.
The message stays until the patient acts. It does not fade out after a few seconds: a message that disappears can vanish before a slow reader, or someone who has looked away, gets to it.
Check it worked
Reload pick-a-time.html and press Continue. After a moment a pale amber banner with an alert icon appears above the slots, reading "10:30 was just taken. These times are still free." The 10:30 slot is crossed out and cannot be selected, and the Continue button still has focus. Choose 10:00 and the banner goes away. Press Continue again and you move to Check your booking.
There, press Book appointment. A pale red banner reads "We could not book this time. Your details are saved." and the button now says "Try again".
Step 4 · Make sure the region is there before the message
A browser announces changes to a live region it already knows about. Three common patterns break that, and each produces a page that looks right and says nothing.
The first is creating the region and its message together:
// Avoid: the region and its text arrive in the same change
const box = document.createElement('div');
box.setAttribute('role', 'status');
box.textContent = '10:30 was just taken. These times are still free.';
document.querySelector('main').prepend(box);Nothing changed inside a region the browser was watching; a whole new region appeared. Some screen readers make an exception for role="alert" added with its text, many do not for status, and support varies across browsers and versions. Do not rely on it.
The second is hiding the region until it is needed, with hidden, display: none or visibility: hidden. A hidden element is left out of the accessibility tree, so the moment you show it and fill it, the region is new again. Hiding it is also what the first instinct for "no gap when empty" leads to. An empty region that takes no space, as in step 1, solves the same problem without leaving the tree.
The third is moving the role. If a framework re-renders the whole banner, including the element with the role, every update replaces the region instead of changing what is inside it. In a component framework, render the region element once in a parent that stays mounted, and render only the message inside it.
The pages you built avoid all three. The div elements with roles are in the HTML when the page loads, they are never hidden, and announce only replaces their children.
Check it worked
Reload pick-a-time.html with the DevTools Elements panel open and <div id="slots-notice" role="status"> visible. It is there and empty before you do anything. Press Continue: DevTools briefly highlights the new <p class="banner"> inside it, while the div itself stays where it was. If you see a whole new div appear instead, the region is being created with its message.
Step 5 · Stop repeat announcements
Leave pick-a-time.html open for a minute after pressing Continue. Every 20 seconds refreshTimes runs and announce replaces the banner with an identical one. The page looks the same, but the region's content was replaced, and some screen readers read the notice again each time. Three polls a minute of "10:30 was just taken" makes the page unusable with a screen reader.
The opposite problem shows up on Check your booking. Press Try again and the booking fails again, with the same words. Screen readers differ in how they treat text swapped for identical text: some read it again, some stay silent. Silence here means the patient thinks their second attempt is still running.
Both come down to one rule: announce events, not renders. Replace announce.js with a version that stays quiet when nothing has changed, and repeats on purpose when the caller says the same words describe a new event:
cd ~/live-region-demo
cat > announce.js <<'JS'
const ALERT_ICON =
'<svg viewBox="0 0 20 20" aria-hidden="true" focusable="false">' +
'<circle cx="10" cy="10" r="8.5" fill="none" stroke="currentColor" stroke-width="2"/>' +
'<path d="M10 5.5v5.5M10 14v.5" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>';
function makeBanner(text) {
const p = document.createElement('p');
p.className = 'banner';
p.innerHTML = ALERT_ICON;
p.append(text);
return p;
}
function announce(region, text, options = {}) {
const same = region.textContent === text;
if (same && !options.repeat) return; // nothing new: stay quiet
if (same) {
// Same words, new event: empty the region, then refill it after a pause.
region.replaceChildren();
setTimeout(() => region.replaceChildren(makeBanner(text)), 150);
return;
}
region.replaceChildren(makeBanner(text));
}
function clearAnnouncement(region) {
region.replaceChildren();
}
JSThe pause matters. If the script empties and refills the region in the same moment, the browser sees one change from the message to the same message, and you are back where you started. Emptying it first and refilling after a short timeout makes two separate changes, so the refill is a new announcement. Emptying a live region is not announced.
You do not need to change app.js. The notice calls announce without repeat, so polls after the first are silent. The error passes { repeat: true }, so every failed attempt is heard. Another option for repeated failures is to change the words, for example "We still could not book this time", which also tells sighted users the second attempt happened.
On a low-end Android phone on a slow or prepaid connection, the booking request can take several seconds, and the patient may have moved on to reading the summary by the time it fails. That is exactly when an announced error earns its keep. If you translate the app, for example into Hausa or Yoruba, and a message is in a different language from the page, put a lang attribute on the banner paragraph so the screen reader switches to the right voice.
Check it worked
Reload both pages and repeat the step 3 checks. On Pick a time, keep the Elements panel open on the status region for a minute after pressing Continue: the banner is no longer re-highlighted every 20 seconds. On Check your booking, press Try again: the banner disappears for a moment and comes back, which is the empty-then-refill you wrote.
Step 6 · Test the accessibility tree with Playwright
You cannot easily record what a screen reader says in an automated test, but you can check what the browser gives it. Playwright's role queries and ARIA snapshots read the accessibility tree, the same structure screen readers use. Install Playwright and its Chromium build in the demo folder:
cd ~/live-region-demo
npm init -y > /dev/null
npm install playwright@1.65.1
npx playwright install chromiumOn Linux, if Chromium later fails to launch with errors about missing libraries, run sudo npx playwright install-deps chromium in the same folder to install them.
Write the check. It loads each page, confirms the region exists and is empty on load, then watches the region with a MutationObserver that counts changes and records the text after each one:
cd ~/live-region-demo
cat > check.mjs <<'JS'
import { chromium } from 'playwright';
import assert from 'node:assert/strict';
const here = new URL('.', import.meta.url).href;
const browser = await chromium.launch();
const page = await browser.newPage();
// Record every change to a region, and keep a handle on the element itself.
const watch = (id) => page.evaluate((id) => {
const region = document.getElementById(id);
window.seen = { region, changes: 0, texts: [] };
new MutationObserver(() => {
seen.changes++;
seen.texts.push(region.textContent);
}).observe(region, { childList: true, subtree: true, characterData: true });
}, id);
// Pick a time: the notice
await page.goto(here + 'pick-a-time.html');
const notice = page.getByRole('status');
assert.equal(await notice.count(), 1, 'one status region on load');
assert.equal(await notice.textContent(), '', 'status region starts empty');
await watch('slots-notice');
await page.getByRole('button', { name: 'Continue' }).click();
await notice.getByText('10:30 was just taken').waitFor();
const noticeTree = await notice.ariaSnapshot();
assert.match(noticeTree, /10:30 was just taken\. These times are still free\./);
assert.doesNotMatch(noticeTree, /img/, 'the icon is hidden from the tree');
assert.ok(await page.evaluate(() => document.getElementById('slots-notice') === seen.region),
'the message went into the region that was there on load');
assert.ok(await page.getByRole('radio', { name: '10:30' }).isDisabled(), '10:30 is disabled');
assert.equal(await page.evaluate(() => document.activeElement.id), 'continue', 'focus did not move');
const changes = await page.evaluate(() => seen.changes);
await page.evaluate(() => refreshTimes());
await page.evaluate(() => refreshTimes());
assert.equal(await page.evaluate(() => seen.changes), changes, 'polls with nothing new change nothing');
console.log('notice ok:\n' + noticeTree);
// Check your booking: the error
await page.goto(here + 'confirm.html');
const alert = page.getByRole('alert');
assert.equal(await alert.count(), 1, 'one alert region on load');
assert.equal(await alert.textContent(), '', 'alert region starts empty');
await watch('booking-error');
await page.getByRole('button', { name: 'Book appointment' }).click();
await alert.getByText('We could not book this time').waitFor();
await page.getByRole('button', { name: 'Try again' }).click();
await page.waitForFunction(() => seen.texts.length === 3);
const message = 'We could not book this time. Your details are saved.';
assert.deepEqual(await page.evaluate(() => seen.texts), [message, '', message],
'a second failure empties and refills the region');
const alertTree = await alert.ariaSnapshot();
assert.match(alertTree, /We could not book this time\. Your details are saved\./);
console.log('error ok:\n' + alertTree);
await browser.close();
JSWhat each assertion proves:
- The region exists and is empty on load, and after the message arrives
document.getElementByIdstill returns the same element. The message went into a region the browser already knew about. - The ARIA snapshot contains the message under the
statusoralertrole and noimg, so the icon is hidden and the role is right. - Focus did not move. The notice is announced, not forced on the user.
- Two polls with nothing new cause no changes. That is the repeat rule for the notice.
- A second failure records the message, then empty, then the message again. That is the deliberate repeat for the error.
Run it:
cd ~/live-region-demo
node check.mjsCheck it worked
The script prints two short ARIA snapshots, something like:
notice ok:
- status:
- paragraph: 10:30 was just taken. These times are still free.
error ok:
- alert:
- paragraph: We could not book this time. Your details are saved.To see the test catch a mistake, add hidden to the status div in pick-a-time.html and run it again. It fails on the first assertion, because a hidden element has no role in the tree. Remove hidden afterwards.
Step 7 · Listen with a screen reader
The test proves the tree is right. Only a screen reader proves the experience is. Use one you have:
- macOS: VoiceOver, switched on and off with Command-F5, with Safari.
- Windows: NVDA, free from nvaccess.org, with Firefox or Chrome.
- Android: TalkBack, under Settings, Accessibility. Put the folder on any web server your phone can reach and open the pages in Chrome.
On Pick a time, move to the Continue button and press it. You should hear the button, then after a moment "10:30 was just taken. These times are still free." without your position moving. Wait a minute: nothing more is read. On Check your booking, press Book appointment: the error is read, usually straight away. Press Try again and it is read again.
Check it worked
You heard each message once per event and your focus stayed on the button you pressed. If you heard nothing, check that the region was on the page before the message, then try another browser: live region support varies between screen reader and browser pairings, which is why testing with at least two pairings is worth the time.
Step 8 · Clean up
Playwright keeps its Chromium download in a shared cache outside the demo folder. Run the uninstall from inside the folder first, so it uses the 1.65.1 you installed. It removes the cached Chromium unless another project on your computer still uses it:
cd ~/live-region-demo
npx playwright uninstallThen remove the demo folder, including the Playwright package:
cd ~
rm -rf ~/live-region-demoNext steps
- Decide which Larkfield messages should be banners, toasts or texts in the first place: design toasts, banners and notifications.
- Live regions are one part of an accessible form. Labels, error summaries and focus management are in build accessible forms in HTML.
- Add automated audits and a full screen reader pass to your routine: test a page for accessibility with axe and a screen reader.
Part of these paths
Related tutorials
- Design toasts, banners and notificationsYou will have a message pattern table that gives every Larkfield Clinic message a channel by urgency and persistence, plus Figma frames for the inline, banner, toast, push and SMS forms, each with a rule for when it goes away.
- How to Build Accessible HTML FormsYou will build a contact form that works with keyboards and screen readers, with real labels, grouped radio buttons, hints tied to their fields, autocomplete values, and an error summary that takes focus and links to each problem, checking the result against specific WCAG 2.2 criteria.
- Test a page for accessibility with axe and a screen readerYou will have a Playwright test that runs axe on the Larkfield Clinic booking page and fails on any new violation, a keyboard test that catches what axe cannot see, and a written checklist for a short screen reader pass.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials