Sub topic 7
Where focus goes when a dialog opens and closes
This chapter assumes you can open a dialog with showModal() and close(). It also assumes you know the inert behavior of the top layer from the previous chapter. Here you will see where keyboard focus lands when a dialog opens, how to change that, and where focus goes when the dialog closes.
Why focus matters
Focus is the element that receives keyboard input right now. Keyboard and screen reader users depend on it. If a dialog opens and focus stays on the button behind it, those users can't tell the dialog appeared. If it closes and focus drops to the top of the page, they lose their place.
A modal dialog opened with showModal() handles most of this for you. You still need to know the rules so you can override them when the default is wrong.
Where focus goes on open
When you call showModal(), the browser picks an element to focus in this order:
- An element inside the dialog that has the
autofocusattribute. - Otherwise, the first focusable element inside the dialog, in document order.
- Otherwise, the dialog itself.
Focusable elements include buttons, links with href, form controls, and anything with a tabindex.
The second rule often goes wrong. If the first focusable element is a Cancel or Close button, that button gets focus. A user who presses Enter immediately has dismissed the dialog without meaning to. Worse, the first element may be a destructive action.
Put autofocus on the element the user most likely needs first. For a form, that is the first input. For a confirmation, it is the safest button.
<button id="delete">Delete project</button>
<dialog id="confirm" aria-labelledby="confirm-title">
<h2 id="confirm-title">Delete this project?</h2>
<p>This cannot be undone.</p>
<form method="dialog">
<button value="delete">Delete</button>
<button value="cancel" autofocus>Keep project</button>
</form>
</dialog>
<script>
const confirmDialog = document.getElementById('confirm');
document.getElementById('delete').addEventListener('click', () => {
confirmDialog.showModal();
});
confirmDialog.addEventListener('close', () => {
console.log('result:', confirmDialog.returnValue);
});
</script>Here the safe button has autofocus. Delete comes first in the markup, so without the attribute the destructive button would take focus.
Keeping focus inside the dialog
While a modal dialog is open, everything outside it is inert. Pressing Tab cycles through the dialog's controls. After the last one, focus moves to the browser's own interface, such as the address bar, and then returns to the dialog. You don't need a JavaScript focus trap or a library.
A non-modal dialog opened with show() has no such behavior. Focus can leave it freely, because the page stays interactive.
Where focus goes on close
When a modal dialog closes, the browser returns focus to the element that was focused when showModal() was called. Usually that is the button the user clicked. The user continues from the same place.
When restoration fails
Focus restoration breaks in a few cases:
- The opener was removed from the DOM while the dialog was open. For example, a list re-rendered and replaced the button.
- The opener is hidden or disabled by the time the dialog closes.
- The dialog was opened from code with no focused element, such as from a timer.
- Some browsers don't focus a button when it is clicked. Safari is the usual example. Then the "previously focused element" may not be the button the user clicked.
In these cases, handle focus yourself. Save a reference to the opener and focus a sensible target in the close event:
const dlg = document.getElementById('confirm');
const opener = document.getElementById('delete');
opener.addEventListener('click', () => dlg.showModal());
dlg.addEventListener('close', () => {
if (dlg.returnValue === 'delete') {
// The opener's row is gone, so move focus to a stable heading.
document.getElementById('page-title').focus();
} else if (document.contains(opener)) {
opener.focus();
}
});For focus() to work on a heading, give it tabindex="-1". That makes it focusable by script but keeps it out of the Tab order.
Common mistakes
- Relying on the first focusable element when it is Cancel or a destructive button.
- Adding
autofocusto several elements. Only the first one counts, so the result is confusing. - Writing a manual focus trap on a modal dialog. The browser already does this, and your code can conflict with it.
- Forgetting a focus target after an action removes the opener.
Exercise
A modal dialog contains a "Close" button first, then a text input, then a "Save" button. Users report that pressing Enter right after the dialog opens closes it. Why does this happen, and what is the smallest fix?
Show answer
With no autofocus element, the browser focuses the first focusable element, which is the Close button, so Enter activates it. Add the autofocus attribute to the text input (or whichever control users need first) so it receives focus when showModal() runs.