A custom alert dialog breaks the moment it fails to announce, hold focus, or dismiss. A backdrop animation does not fix that. window.alert() already gives you keyboard access and a screen-reader interruption. A hand-rolled modal throws those guarantees away unless you rebuild them, and you only need that replacement when the message has structure or two labelled choices.
Modals are ordinary UI now. In 2025, the Web Almanac recorded the ARIA dialog role on 34.05% of desktop pages and 36.01% of mobile pages globally, and the alert role on 7.12% of desktop pages and 6.74% of mobile pages. JavaScript is still how UK teams build these interactions: 63% of 3,224 surveyed UK developers used it, according to Stack Overflow’s 2024 Developer Survey as reported by CMO Today UK.
Dialogs that fire on page entry or exit cut the journey short. I split the work into announcement, focus and dismissal, and I want a failing test for each: the screen reader stays quiet, focus leaves the dialog, or neither Escape nor the labelled close control dismisses it. Fix the failing behaviour before you polish the skin.
Table of Contents
- Choose the Right Alert Mechanism First
- Write the Accessible Markup Before the JavaScript
- How to Add Focus Handling and Keyboard Control
- Fix the Failures Browsers and Screen Readers Expose
- Test the Dialog Before It Ships
- Decide Whether to Build or Adopt
Choose the Right Alert Mechanism First
Treat showModal() on a native <dialog> as the default for any custom alert. It gives you the browser’s top layer, Escape dismissal and an inert background. You do not rebuild that plumbing in script.
Compare the five mechanisms before you write a line of JavaScript. The fork is architectural: a native prompt, <dialog>, or a manual <div>.

window.alert() fails as soon as the message needs structure. As W3C WAI’s forms notifications guidance points out, a browser alert supplies keyboard access and follows the user’s font size, colours and language. It still renders plain text, offers one OK button, and freezes script execution. Two clearly labelled outcomes are impossible.
Reserve a hand-rolled <div role="alertdialog"> for legacy browsers that lack <dialog>. In that case you own every piece of state: background isolation, the focus trap and Escape.
Alert mechanisms compared
| Mechanism | Keyboard and focus handled for you | Accessible name and role | Where it falls short | Use it when |
|---|---|---|---|---|
window.alert() |
Yes, fully browser-controlled | Browser-supplied | Plain text only, one OK button, blocks the whole page, cannot be styled | Short blocking confirmation with no choices |
confirm() / prompt() |
Yes | Browser-supplied | OK/Cancel only, no custom labels or structure, often blocked in embedded frames | Quick two-choice confirmation |
<dialog> with showModal() |
Escape, top layer, outside content inert | You set aria-labelledby and the dialog role is implicit |
Focus trap needs help for cyclic tabbing in some browsers | Default for custom alert dialogs |
<dialog> with show() |
No, it is non-modal | You set it yourself | Page stays operable behind it | Non-blocking advisory content |
div with role="alertdialog" |
No, you build all of it | You set it yourself | Background isolation, focus trapping, Escape all manual | Legacy browser support only |
The wrong row shows up as the same failure groups UK public-sector monitoring already records. The UK government’s public-sector accessibility monitoring report for February 2020 to November 2021 recorded 2,691 accessibility issues across 421 website tests. 12% involved Focus Visible, 11% involved Name, Role, Value, and 8% involved Keyboard. Together those three groups made up 31% of logged issues. They map onto announcement, focus and dismissal.
Announcement is Name, Role, Value. window.alert(), confirm() and prompt() supply the name and role. With <dialog> or a custom div, you set aria-labelledby. The test: open the dialog with a screen reader and confirm the title is announced, not the control that opened it.
Focus is Focus Visible. showModal() moves focus into the top layer and makes the page behind inert. show() and a plain div do not. Tab once. If focus stays on the page under the overlay, the mechanism is wrong.
Dismissal is Keyboard. Escape closes a modal <dialog> and should return focus to the trigger. show() leaves the page operable, so Escape is not a close gesture unless you add one. On a custom div, Escape, the trap and the return of focus are all your code. If Escape does nothing, you chose a mechanism that never promised it.
Decision rule: If you’re choosing
<dialog>, reach forshowModal()on blocking alerts andshow()only when the user should keep interacting with the page underneath.
When a message shouldn’t be a dialog at all
Routine status, form validation and low-risk confirmation do not need a modal. Inline text, an ARIA live region, or a non-blocking toast notification pattern lets someone finish typing without losing their place. A modal steals that place. A toast does not.
Progressive enhancement still applies. If the action matters, back the trigger with a normal form submission or a confirmation URL. The dialog can improve that path. It must not be the only way the task completes when the script fails to load.
Write the Accessible Markup Before the JavaScript
Good alert dialog JavaScript starts with semantic HTML that already explains itself to assistive technology. Under the UK government’s accessibility guidance for developers, public-sector services must meet WCAG 2.2 Level AA, and automated scanners catch only around 30% of likely accessibility issues. If your underlying markup omits an accessible name or puts buttons in a risky order, no amount of event listeners will paper over the gap.

Start by pasting this complete skeleton into your page before attaching any behaviour.
<form action="/account/delete-confirm" method="get">
<button type="submit" id="open-delete-dialog">
Delete account
</button>
</form>
<dialog
id="delete-confirm"
aria-labelledby="delete-title"
aria-describedby="delete-desc"
>
<header class="dialog-header">
<h2 id="delete-title">Delete this account permanently?</h2>
<button
type="button"
class="dialog-close"
value="cancel"
aria-label="Close"
>
×
</button>
</header>
<p id="delete-desc">
All saved projects and billing history will be removed immediately.
This action cannot be undone.
</p>
<footer class="dialog-actions">
<button type="button" id="cancel-delete" value="cancel">
Cancel
</button>
<button type="button" id="confirm-delete" value="confirm">
Delete account
</button>
</footer>
</dialog>
Notice the trigger sits inside a real <form> pointing at a server-rendered confirmation route. If JavaScript fails or is blocked, clicking the button still goes to a working confirmation page; when your script loads, it intercepts the click and upgrades the flow to the modal. For purely client-side actions with no server route, use <button type="button"> so you never trigger an unintended form submit.
Attributes that carry accessibility weight
Every attribute on that <dialog> earns its keep, while several common ones are deliberately left out.
- Stable
idandaria-labelledby: Pointingaria-labelledbyat#delete-titlegives the dialog an explicit accessible name from visible text, rather than relying on fragilearia-labelstrings that drift out of sync with the heading. - Linked
aria-describedby: Referencing#delete-desctells screen readers to announce the consequence immediately after the dialog title and role, so users don’t have to hunt for what they’re confirming. - Implicit role versus
role="alertdialog": A native<dialog>already exposes thedialogrole, which suits calmer interactions like editing settings or previewing details. Reservealertdialogfor interrupting messages that demand an immediate response, such as destructive deletions or blocking errors, and remember you only need an explicitroleattribute on a legacy<div>modal where no native element exists. - No redundant
aria-modal="true": CallingshowModal()impliesaria-modal="true"in the accessibility tree automatically, so adding the attribute by hand adds noise without improving support. - Button order and explicit labels: Put the non-destructive
Cancelbutton first in DOM order so keyboard users don’t land straight on a destructive action. Two labels show up repeatedly in UK audits: icon-only close buttons missingaria-label="Close", and vague confirmation buttons reading “OK” instead of stating the consequence like “Delete account”.
Keep any essential warning text visible inside the DOM rather than hiding it behind CSS toggles. If the user needs a piece of information to decide safely, it must remain available in both the scripted modal and the no-JavaScript fallback page.
How to Add Focus Handling and Keyboard Control

A modal <dialog> gives you a head start, not a finished component. W3C WCAG technique H102 notes that a modal HTML dialog makes outside page content inert and unavailable to assistive technology, which means opening a dialog prematurely or scoping it poorly can hide vital context from screen-reader users. Announcement, focus placement and dismissal still have to be wired deliberately in your script.
This seven-step sequence maps the exact focus lifecycle your script needs to control from click to close.
Work through these seven steps against the HTML skeleton above. Each step targets a specific production bug.
- Capture the opener before opening the modal. Store
opener = document.activeElementbefore you callshowModal(). Once the modal opens, the browser shifts focus immediately, so readingdocument.activeElementinside a later handler gives you the wrong node. - Open with
showModal(), nevershow(). Intercept the trigger’s click event, callevent.preventDefault()on the fallback form submission, and invokedialog.showModal(). Callingshow()leaves the page underneath clickable and reachable by Tab, which breaks modal expectations on a blocking alert. - Focus the safest control on entry. Move focus explicitly to
#cancel-delete(or to#delete-titlewithtabindex="-1"if the message is long and needs reading before any button). That prevents an accidental double-tap on Enter from deleting an account, and ensures the heading and warning are announced clearly. - Trap
TabandShift+Tabinside the dialog. Although<dialog>marks outside content inert, browsers differ on whether tabbing off the last button wraps back to the first or jumps into the browser address bar. Query visible, enabled focusable elements inside the dialog onkeydownand wrap manually; if your modal still drops keyboard focus, keyboard fixes from the Vision team cover common tab-order traps worth checking. - Respect
Escapethrough thecancelevent. A modal<dialog>fires acancelevent when the user pressesEscape. Let it close naturally unless you need a secondary confirmation step, in which case callevent.preventDefault()explicitly. - Restore focus inside the
closeevent. Listen fordialog.addEventListener('close', ...)rather than duplicating focus code across every button handler. Checkif (opener && opener.isConnected)before callingopener.focus()so a removed DOM node never throws focus back todocument.body. - Inspect
dialog.returnValueto branch cleanly. Pass'confirm'or'cancel'intodialog.close(value)so thecloselistener knows whether to execute the destructive request or exit.
Steps one, six and seven deserve extra attention because they fail without warning. Nothing throws an error when focus lands on document.body after close; the keyboard user loses their place mid-page and has to tab through the header navigation again. That kind of breakage rarely surfaces in automated tests, so I recommend scripting a manual pass with only the keyboard before signing off any destructive dialog.
If you’d rather see how native focus flow and keyboard trapping behave live in the browser before pasting the code, this short walkthrough demonstrates the interaction end to end.
Isolating the background on legacy custom divs
When legacy browser support forces a <div> with role="alertdialog", background isolation becomes your responsibility. Set the inert attribute on your main page container alongside aria-hidden="true" while the dialog is open, then remove both on close. This pairing is worth keeping even where inert alone appears sufficient: public-sector design systems in the UK still document the combination as the dependable pattern, because aria-hidden covers assistive technology that predates or mishandles the inert attribute.
The order of operations matters here too. Apply inert and aria-hidden before moving focus into the dialog, and reverse that order on close: restore focus to the opener first, then unhide the background. Reversing the close sequence leaves focus inside a hidden subtree for a frame or two, which some screen readers announce as the whole page disappearing.
Complete paste-ready alert dialog script
Drop this script below the HTML from the previous section. It combines all seven steps in roughly 40 lines with zero external dependencies.
const trigger = document.getElementById('open-delete-dialog');
const dialog = document.getElementById('delete-confirm');
const cancelBtn = document.getElementById('cancel-delete');
const confirmBtn = document.getElementById('confirm-delete');
const closeBtn = dialog.querySelector('.dialog-close');
const FOCUSABLE = 'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';
let opener = null;
function getFocusable(container) {
return [...container.querySelectorAll(FOCUSABLE)].filter(
(el) => el.offsetParent !== null && !el.hasAttribute('disabled')
);
}
trigger.addEventListener('click', (event) => {
event.preventDefault();
opener = document.activeElement;
dialog.showModal();
requestAnimationFrame(() => cancelBtn.focus());
});
dialog.addEventListener('keydown', (event) => {
if (event.key !== 'Tab') return;
const items = getFocusable(dialog);
if (!items.length) return;
const first = items[0];
const last = items[items.length - 1];
if (event.shiftKey && document.activeElement === first) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && document.activeElement === last) {
event.preventDefault();
first.focus();
}
});
cancelBtn.addEventListener('click', () => dialog.close('cancel'));
closeBtn.addEventListener('click', () => dialog.close('cancel'));
confirmBtn.addEventListener('click', () => dialog.close('confirm'));
dialog.addEventListener('cancel', () => {
dialog.returnValue = 'cancel';
});
dialog.addEventListener('close', () => {
if (opener && opener.isConnected) opener.focus();
if (dialog.returnValue === 'confirm') {
// Trigger your API call or submit the confirmed action here
}
});
Two details in this script are easy to overlook. The getFocusable filter checks offsetParent because elements hidden with display: none or inside a collapsed container still match the selector string but cannot receive focus, which is exactly what breaks a trap when a hidden close icon ends up first in the list. And the cancel listener writes 'cancel' into returnValue so that Escape, the close button and the Cancel button all resolve to the same outcome in the close handler, keeping your confirmation logic in one place.
Fix the Failures Browsers and Screen Readers Expose
Shipping a working prototype on one machine rarely means the dialog holds up everywhere. In 2025, research by Warbox reported by PPC Land found that 48% of more than 1,200 UK websites across 14 sectors required accessibility improvements, specifically noting that JavaScript implementations can create real difficulties for people relying on assistive tools. Understanding accessibility risks in UK digital services makes it clear why a broken confirmation modal isn’t a minor UI glitch; it can lock disabled customers out of checkout, account recovery or consent settings.
When a dialog misbehaves in testing, diagnose it in this exact order before editing code:
- Check the announced name first. A screen reader announcing only “dialog” almost always traces back to an empty, misspelled or hidden
aria-labelledbytarget. - Check initial focus placement. If focus stays stranded on the background page,
showModal()likely ran before the modal’s inner DOM finished painting. - Check the focus trap selector. Tabbing out to the address bar happens when your query includes hidden, zero-size or disabled elements that can’t receive focus.
- Check
Escapehandling. A silentEscapekey usually means akeydownlistener swallowed the event withpreventDefault()and never calleddialog.close().
Once you’ve isolated which stage is failing, match the visible symptom to its root cause and code change below, and verify cross-engine behaviour against known browser compatibility quirks before closing the ticket.
Alert dialog symptoms, causes and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
| Focus stays on the page after opening | showModal() runs before content is painted |
Defer the focus call with requestAnimationFrame |
| Screen reader announces only “dialog” | aria-labelledby targets an empty or missing heading |
Point it at the visible heading id |
| Tab moves out to the browser toolbar | Trap counts hidden, disabled or zero-size controls | Filter on offsetParent and the disabled attribute |
| Escape does nothing | A keydown handler calls preventDefault() and never closes |
Handle the cancel event and let it close |
| Focus returns to the body on close | Opener was re-rendered and the reference is stale | Store the opener id and re-query on close |
| Message is not read out | aria-describedby target is display:none |
Keep the message in the accessibility tree |
| Dialog sounds more urgent than it is | role="alertdialog" on a routine confirmation |
Reserve alertdialog for interrupting, blocking messages |
Two edge cases that slip past quick fixes
First, watch for role misuse in shared modal wrappers. Say a product team builds one generic confirmation component and hard-codes role="alertdialog" onto it. Every harmless prompt (“Export CSV?”) then interrupts screen-reader users with urgent alert semantics, creating fatigue that causes people to tune out genuine warnings.
Second, guard against stale opener references inside reactive lists. Say a user clicks “Delete” on row four of a table, confirms inside the dialog, and the framework re-renders or removes that row before the close event fires. Keeping a direct DOM node reference fails because the old button is gone; store the trigger’s stable id (or fall back to the next row’s action button or the table heading) and re-query the DOM on close.
Never trust a fix until you watch focus move in the browser’s accessibility inspector and hear the announcement change in a real screen reader.
Test the Dialog Before It Ships
Treat accessibility testing as a hard release gate, not a post-launch tidy-up. Every alert dialog should clear five checks with recorded pass evidence before the pull request merges.

Five pre-release checks and pass conditions
- Keyboard pass across three engines. Trigger the dialog using both
EnterandSpace, pressTabandShift+Tabthrough every interactive element to confirm the cycle wraps cleanly, then pressEscapeand verify focus lands back on the trigger. Repeat in Chrome, Firefox and Safari because modal tab cycling behaves differently across browser engines. Pass condition: zero focus loss and zero tabs escaping into the background page or browser chrome. - Screen-reader pass on real pairings. Run NVDA with Firefox on Windows and VoiceOver with Safari on macOS, following a repeatable screen-reader testing workflow. Confirm the dialog announces its accessible name, description and role in a logical order without skipping the warning copy. Pass condition: a blind user can hear what the alert asks, distinguish both actions and confirm dismissal without guessing.
- Zoom and narrow-viewport reflow. Test the open dialog at 400% browser magnification and inside a 320 px wide viewport. Wide side-by-side button footers are the most common culprit for clipped text and horizontal overflow; switch the footer to a stacked vertical layout on narrow screens and allow internal scrolling (
max-block-size: 90dvb; overflow-y: auto). Pass condition: all text and controls remain readable and reachable with zero horizontal scrolling. - High contrast and reduced motion. Toggle Forced Colours / Windows High Contrast mode to confirm focus outlines, dialog borders and close icons don’t vanish against the backdrop. Enable
prefers-reduced-motion: reduceand verify any fade or scale transition disables cleanly. Pass condition: every focus ring and control boundary stays clearly visible, and motion stops when requested. - Automated smoke test paired with manual notes. Run axe DevTools or Lighthouse in your browser and wire regression checks into CI by applying how to design robust UI tests. Because automated tools only catch a subset of structural errors, treat a clean scan as a baseline rather than proof of compliance. Pass condition: zero automated critical violations, stored alongside written manual test notes in the pull request.
Release gate: Do not ship until there are zero unresolved critical keyboard or screen-reader defects across every tested browser and assistive-technology combination.
Decide Whether to Build or Adopt
A 40-line alert dialog script is small enough for a senior engineer to audit in an afternoon. Owning that JavaScript gives you direct control of bundle size and markup. Focus rules move. When Safari, Firefox or Chromium changes <dialog> top-layer behaviour, your team owns the retest and the regression fix.
A maintained component library shifts that browser work onto its maintainers. You still pin the version, audit the dependency, and recheck the dialog after every upgrade. If the app is Vue and you want focus management and screen-reader behaviour without writing the trap yourself, DOM Studio is one library to shortlist. Its Components library includes menus, dialogs, tabs and other app primitives built as standards-based web components. I would not adopt any dialog until its demo survives the same five pre-release checks you already run on custom markup.
Technical accessibility isn’t ethical design
A dialog can pass every WCAG test and still steer the user toward the choice the business prefers.
In January 2025, the Information Commissioner’s Office (ICO) reported assessing the top 1,000 UK websites and raising concerns with 134 organisations over giving people meaningful control over tracking. Consent banners on high-traffic UK sites have drawn the same kind of scrutiny for dark patterns: rejection harder to reach than acceptance, optional tracking treated as the default, and personal data handled before a real choice.
Pair the accessible markup with honest choice architecture on every consent, deletion or payment modal:
- Keep primary actions symmetric: Give “Reject non-essential” the same visual weight and click depth as “Accept all”.
- Never preselect optional consent: Leave non-essential toggles unchecked by default so consent reflects an active choice.
- Default to the safe path: Make the non-destructive action the initial focus target on deletions, cancellations and irreversible billing changes.
Pick the next modal in the sprint backlog and attach the keyboard and screen-reader notes to the pull request. If custom focus traps, keyboard cycling and ARIA wiring across every modal cost more than the control is worth, headless dialog primitives and Vue components can supply those behaviours and keep the bundle small. Inspect how the dialogs behave in the catalogue at DOM Studio.
