- Published on
- 2 min read
A modal is a focus journey
- Authors
- Name
- Ritenta
A modal is more than a box above the page. Opening it changes where a keyboard user can go. If focus stays behind the overlay, the visible dialog and the active control disagree. If closing it drops focus at the top of the page, the user has to find their place again.
Begin with the platform
For an ordinary modal, native <dialog> with showModal() supplies modal behavior, including making the rest of the document inert while it is open. Give it a visible heading and a close control. Choose an initial focus target that makes sense for the task, and remember the button that opened it so you can return focus if that button still exists. See MDN's dialog reference and the W3C modal dialog pattern.
<button id="open-settings" type="button">Edit settings</button>
<dialog id="settings" aria-labelledby="settings-title">
<h2 id="settings-title">Edit settings</h2>
<label>Display name <input name="displayName"></label>
<button id="close-settings" type="button">Close</button>
</dialog>
const opener = document.querySelector('#open-settings');
const dialog = document.querySelector('#settings');
opener.addEventListener('click', () => dialog.showModal());
document.querySelector('#close-settings').addEventListener('click', () => dialog.close());
dialog.addEventListener('close', () => {
if (opener.isConnected) opener.focus();
});
The snippet illustrates the focus return. A real form also needs a save action and a decision about whether Escape discards unsaved work. Native behavior does not make those product choices for you.
Walk the whole route
Test opening with Enter and Space, moving forward and backward through controls, closing with the button and Escape, and returning to the launcher. The W3C pattern keeps Tab within a modal and expects focus to move inside when it opens. For long explanatory content, the best initial target may be a heading with tabindex="-1" instead of the first input. Decide from the dialog's content and test with assistive technology.