Keyboard-Friendly Native Dialogs From Opening to Focus Return
A keyboard user opens a settings dialog from a long list. They need to know which dialog appeared, find the first control, and return to the list at the place where they started. Each of those steps can fail even when the screenshot looks right. Native HTML provides the modal behavior, while the page still determines the accessible name, the initial task, and the destination after close.
Open with the browser’s modal operation
Call showModal() on a connected <dialog>. The browser places the dialog in the top layer and makes the surrounding content of its document inert while the modal is active. That scope matters if the dialog is inside an iframe. The embedding page has its own document. The same element also offers show() for a modeless dialog, where users can continue to interact with the page.
Give the modal a visible heading and connect it using aria-labelledby. For a short confirmation, aria-describedby can point to one sentence that explains the consequence. For structured content with headings, lists, or a table, let the user navigate that structure. A single long accessible description makes it harder to read the sections independently. Set styling on dialog::backdrop and preserve a visible focus indicator on interactive controls.
Choose the first focus for the task
For a small settings form, set autofocus on the field most people open the dialog to change. For a long explanation, the APG recommends considering initial focus on an element near the start of the content, such as the heading with tabindex="-1". In that case, show the modal and focus the heading programmatically. Put the attribute on the heading or another suitable descendant. The HTML Standard disallows tabindex on the dialog element itself.
For an irreversible confirmation, initial focus can land on the least destructive action. Check the visible result at high zoom. A focused button below the fold may cause the title to scroll away, and a sticky footer can cover the focused field. In a scrollable layout, leave room around focus targets and check them using the actual keyboard. WCAG 2.2 criterion 2.4.11 requires a focused component to remain at least partially visible when author-created content overlaps it.
Keep cancellation separate from applying a choice
This example stores a display preference for the lifetime of the page. It reports the saved choice in a status region. An application can use the same value to render its list.
<button id="open-density" type="button">Change list density</button>
<p id="density-status" role="status"></p>
<dialog id="density-dialog" aria-labelledby="density-title">
<h2 id="density-title">List density</h2>
<form method="dialog">
<label for="density-choice">Display mode</label>
<select id="density-choice" autofocus>
<option value="comfortable">Comfortable</option>
<option value="compact">Compact</option>
</select>
<button type="submit" value="cancel">Cancel</button>
<button type="submit" value="apply">Apply</button>
</form>
</dialog>
<script>
const openButton = document.querySelector('#open-density');
const dialog = document.querySelector('#density-dialog');
const choice = document.querySelector('#density-choice');
const statusMessage = document.querySelector('#density-status');
let density = 'comfortable';
openButton.addEventListener('click', () => {
if (dialog.open) return;
choice.value = density;
dialog.returnValue = '';
dialog.showModal();
});
dialog.addEventListener('close', () => {
if (dialog.returnValue !== 'apply') return;
density = choice.value;
const label = choice.selectedOptions[0].textContent;
statusMessage.textContent = `List density set to ${label}.`;
});
</script>
A form with method="dialog" closes the dialog locally and sets returnValue from the submit button. Escape normally requests dismissal. Reset the value on every opening because the previous value can survive a close that supplies no new one. Without that reset an Apply followed by Escape on a second visit could be mistaken for another Apply. Likewise, seed the field from the saved state so an abandoned selection does not leak into the next visit.
Use the dialog methods for lifecycle changes. Removing the open attribute directly can skip the close event and leave the document blocked. For an action that must wait for a server, use a regular submit handler, keep the dialog open while the request runs, and close after success. Show any failure inside the dialog and restore access to the form controls. A visible Cancel or Close button gives pointer, keyboard, and assistive technology users an explicit exit.
Decide where work resumes
The browser normally restores the element focused before the modal opened. Test that the opener really had focus, especially for pointer activation or framework-driven opening. If it is missing after the action, set focus to a stable element that follows the workflow. For example, after removing a list item, use the next item’s action, the previous item’s action if there is no next item, or the list heading when empty. Give a fallback heading tabindex="-1" so it can receive programmatic focus without adding it to the ordinary tab order.
An end-to-end browser test can assert focus on open and after both Cancel and Escape. Add an Apply followed by a new open, a different selection, and Escape. The previous saved choice should remain. With the dialog open, use Tab and Shift+Tab to verify that focus never reaches background page controls. Test a removed opener, then check the narrow layout at high zoom. Finally, run the same flow with a screen reader and verify that it announces the dialog name, the active field, and the result when the setting is applied.