Manage focus in a modal dialog
Use the modal pattern, provide an accessible name, choose initial focus, and return focus when the dialog closes.

A modal dialog needs more than a visual overlay. It should have an accessible name, place focus appropriately inside, keep keyboard interaction within the modal while open, and return focus to a useful location when closed. Prefer a tested native or established implementation over hand-building a focus trap casually.
Name the dialog and the task
For a fictional confirmation dialog, the title might be “Delete saved draft?” The controls should make the consequence clear. The W3C modal dialog pattern describes naming, focus behavior, keyboard interaction, and returning focus. Use it as a reference for the complete behavior.
A native starting point
<button id="open">Review deletion</button>
<dialog id="confirm" aria-labelledby="confirm-title">
<h2 id="confirm-title">Delete saved draft?</h2>
<p>This action removes the draft from this device.</p>
<form method="dialog">
<button value="cancel">Keep draft</button>
<button value="confirm">Delete draft</button>
</form>
</dialog>This is markup for an example, not the complete application logic. Use showModal() to open a native modal dialog, handle the result, and perform deletion only after the confirmed action. The description of deletion must match what your system actually does.
Choose initial focus deliberately
For a destructive action, a safe initial focus may be the cancel control. For a long informational dialog, focusing the beginning of the content may help. The correct choice depends on the task; do not always focus the first input just because it exists.
Test opening and closing
- Open with the keyboard and inspect initial focus.
- Tab forward and backward through the dialog.
- Close with the intended cancel or Escape path.
- Check focus returns to the trigger, or a sensible replacement if it disappeared.
- Confirm background content is not accidentally interactive while modal.
Motion around the dialog should not delay focus or prevent cancellation. Provide a reduced-motion path if it slides or scales. Test the complete component in your target browsers and assistive technologies; a copied fragment does not establish that your implementation follows the full modal pattern.
References and further reading
The examples and templates above are original. These references support the definitions and documented behavior discussed in the guide.



