Sub topic 7
Where Focus Goes When a Dialog Opens and Closes
This chapter assumes you can open and close a <dialog> with showModal(), show() and close(). It also assumes you know what autofocus does on a form control, and that you can read basic DOM event code. Here you will learn which element receives focus when a dialog opens, where focus goes when it closes, and how to override both behaviors when the defaults are wrong.
Why focus matters for dialogs
Focus is the element that receives keyboard input right now. A mouse user sees a dialog appear and moves on. A keyboard or screen reader user depends on focus to learn the dialog exists. If focus stays behind the dialog, they type into a page they can't see. If focus is lost when the dialog closes, they have to find their place again.
The browser handles both ends of this for you. You need to know the rules because the defaults are sometimes the wrong choice, and because some changes you make while the dialog is open (such as removing the button that opened it) defeat the restore step.
What happens when the dialog opens
When you call showModal() or show(), the browser runs the dialog focusing steps. In practice they work like this:
- If a descendant of the dialog has the
autofocusattribute, that element gets focus. - Otherwise, the first focusable element in document order gets focus.
- If the dialog contains nothing focusable, the dialog element itself gets focus.
The browser also records which element had focus just before the dialog opened. It uses that record when the dialog closes.
A focusable element is one the user can focus: a link with href, a non-disabled button or form control, or an element with a tabindex attribute. Elements with tabindex="-1" are focusable by script and by autofocus, but not by Tab.
Take the dialog from the earlier chapters:
<dialog id="dlg" aria-labelledby="dlg-title">
<h2 id="dlg-title">Edit profile</h2>
<form method="dialog">
<label>Name <input name="name" required autofocus></label>
<menu>
<button value="cancel" formnovalidate>Cancel</button>
<button value="save">Save</button>
</menu>
</form>
</dialog>Here autofocus puts the cursor in the name field. Without it, the first focusable element in document order is the same input, so the result would be identical. The attribute matters when the first focusable element is not the one you want.
Choosing the right initial focus
The default can be wrong in a few common cases. This table lists them, with a fix for each.
| Situation | Default result | Better choice |
|---|---|---|
| Destructive confirmation ("Delete this file?") | First button, often the destructive one | `autofocus` on Cancel |
| Dialog starts with a close (×) button | The close button | `autofocus` on the main field or primary action |
| Long text, such as terms of service | First focusable element, which may scroll the content past its start | `tabindex="-1"` on the heading, with `autofocus` on it |
| Dialog with no focusable content | The dialog element | Usually fine, but add a close button |
For a destructive confirmation, put autofocus on the safe option:
<dialog id="confirm" aria-labelledby="confirm-title">
<form method="dialog">
<h2 id="confirm-title">Delete this file?</h2>
<p>This cannot be undone.</p>
<menu>
<button value="delete">Delete</button>
<button value="cancel" autofocus>Cancel</button>
</menu>
</form>
</dialog>Now a user who opens the dialog and presses Enter by reflex cancels instead of deleting.
For long content, a heading can take focus. Add tabindex="-1" so the heading is focusable, then mark it with autofocus:
<dialog id="terms" aria-labelledby="terms-title">
<h2 id="terms-title" tabindex="-1" autofocus>Terms of service</h2>
<p>Long text goes here.</p>
<form method="dialog">
<button value="accept">Accept</button>
</form>
</dialog>Focus starts at the top of the text. A screen reader announces the heading, and the next Tab press reaches the Accept button.
Focus while the modal is open
showModal() makes everything outside the dialog inert, which means it can't be clicked, selected or focused. Tab and Shift+Tab therefore cycle through the dialog's controls only.
The cycle is not a strict trap. After the last control, Tab moves focus out to the browser interface (address bar, toolbar) and then back into the dialog. This is intentional, because it keeps the browser's own controls reachable. You do not need a script that traps focus, and writing one usually makes things worse.
A non-modal dialog opened with show() behaves differently. The rest of the page stays interactive, so Tab moves freely between the dialog and the page. The dialog gets initial focus, but nothing keeps focus inside it.
What happens when the dialog closes
When the dialog closes by close(), Escape, or a method="dialog" form submit, the browser returns focus to the element that was focused when the dialog opened. Normally that is the button the user pressed. A keyboard user ends up exactly where they were.
The sequence is: the dialog closes, focus is restored, and then the close event fires. That order matters in the next section, because focus code in a close handler runs after the restore and overrides it.
When the restore does not work
Focus restoration fails or surprises you in these cases:
- The opener was removed or hidden. If the recorded element is no longer in the document, there is nothing to focus. Focus falls back to the page body, and a keyboard user starts again from the top of the page.
- The opener never had focus. Some browsers, notably Safari on macOS, do not focus a button when it is clicked with the mouse. The browser then records no useful element, and nothing meaningful is restored. Keyboard activation does focus the button, so this mostly affects mouse users who then switch to the keyboard.
- The dialog was opened from script with no user interaction. If focus was on the body, focus goes back to the body.
- The result changes what should come next. Returning to the opener is the right default for cancel. After a successful action, such as deleting an item, the best target might be somewhere else.
Taking control of focus on close
Use the close event to set focus yourself. The next example removes a list item after a confirmed delete. The opener button disappears with the item, so the browser cannot restore focus to it. The handler moves focus to the next item's Delete button, or to the list heading if there is none.
<h2 id="list-title" tabindex="-1">Files</h2>
<ul id="items">
<li>Report <button class="delete">Delete</button></li>
<li>Budget <button class="delete">Delete</button></li>
<li>Notes <button class="delete">Delete</button></li>
</ul>
<dialog id="confirm" aria-labelledby="confirm-title">
<form method="dialog">
<h2 id="confirm-title">Delete this file?</h2>
<menu>
<button value="delete">Delete</button>
<button value="cancel" autofocus>Cancel</button>
</menu>
</form>
</dialog>
<script>
const items = document.getElementById('items');
const title = document.getElementById('list-title');
const confirmDialog = document.getElementById('confirm');
let opener = null;
items.addEventListener('click', (event) => {
const button = event.target.closest('.delete');
if (!button) return;
opener = button;
confirmDialog.returnValue = ''; // clear the value from the previous use
confirmDialog.showModal();
});
confirmDialog.addEventListener('close', () => {
if (confirmDialog.returnValue !== 'delete') return; // browser restored focus
const item = opener.closest('li');
const next = item.nextElementSibling?.querySelector('.delete');
item.remove();
(next ?? title).focus();
});
</script>Three details in this code are worth noting:
- The handler returns early for Cancel and Escape, so the browser's own restore stands.
returnValuekeeps its previous value between openings. If the user deleted one file and then pressed Escape on the next dialog,returnValuewould still read"delete". Resetting it beforeshowModal()avoids deleting the wrong item.- The heading has
tabindex="-1"sotitle.focus()works. It is focusable by script but does not add a Tab stop.
Focus and the `:focus-visible` outline
Programmatic focus does not always show a focus ring. Browsers apply :focus-visible rules: after a keyboard interaction they draw the ring on a script-focused element, and after a mouse click they often do not. A heading focused with tabindex="-1" usually shows no ring for mouse users, which is the right result. Do not remove outlines globally with outline: none, because keyboard users depend on them. If you restyle the ring, do it on :focus-visible:
dialog :focus-visible {
outline: 3px solid #1a5fb4;
outline-offset: 2px;
}Common focus mistakes
- Writing a focus trap for a modal dialog. The browser already confines Tab, and a custom trap can lock keyboard users away from browser controls.
- Calling
focus()on an element inside the dialog before it is open. The element is not rendered yet, so the call does nothing. CallshowModal()first, or useautofocus. - Using
autofocuson several elements. Only one wins, and the choice is hard to predict. Use it once per dialog. - Removing the opener and expecting a restore. Move focus yourself in the
closehandler, as in the delete example. - Forgetting that
returnValuepersists. Reset it before eachshowModal()if your logic branches on it.
Exercise
A confirmation dialog contains a "Delete" button followed by a "Cancel" button, and neither has autofocus. A keyboard user opens the dialog and presses Enter immediately. What happens, and what is the one-attribute fix?
Show answer
The browser focuses the first focusable element, which is the Delete button, so Enter confirms the destructive action. The fix is to add autofocus to the Cancel button, so the safe option receives initial focus.
Exercise
A user clicks a row's Delete button, confirms in a modal dialog, and your code removes that row from the page. Where does focus go after the dialog closes if you write no focus code, and how do you fix it?
Show answer
The browser tried to restore focus to the Delete button, but that button was removed from the document, so focus falls back to the page body and a keyboard user loses their place. In the dialog's close handler, check that returnValue is the confirm value, remove the row, and call focus() on a stable target such as the next row's Delete button or the list heading (which needs tabindex="-1"). The close event fires after the browser's restore step, so your call wins.
Exercise
Why can you rely on the browser to keep Tab inside a modal dialog but not inside a dialog opened with show()?
Show answer
showModal() makes the rest of the page inert, so only the dialog's controls (and the browser's own interface) can receive focus. show() leaves the page interactive, so Tab moves freely between the dialog and the page. A non-modal dialog gets initial focus, but nothing confines focus to it.