Dialogs that behave like dialogs
Open a modal dialog
Use dialog and showModal() to open the task editor with browser-managed modality, focus, and a backdrop.
A modal task editor interrupts the current workflow and asks the user to finish or dismiss one focused interaction. The dialog element gives that interaction a real browser primitive instead of a positioned div that merely looks modal.
Call showModal() to put the dialog in the top layer. The browser makes the rest of the document inert, exposes modal semantics, and supports ::backdrop styling. A plain open attribute or show() displays a non-modal dialog and does not provide the same boundary.
<button type="button" id="add-task">Add task</button>
<dialog id="task-dialog">
<form method="dialog">
<h2>Add a task</h2>
<label>Title <input name="title" autofocus></label>
<button value="cancel">Cancel</button>
<button value="save">Save</button>
</form>
</dialog>
<script>
const addTask = document.querySelector("#add-task")
const taskDialog = document.querySelector("#task-dialog")
addTask.addEventListener("click", () => taskDialog.showModal())
</script>
The dialog should have an accessible name. A visible heading in the dialog supplies useful context; aria-labelledby can connect it explicitly when needed. Keep the dialog focused on one job rather than moving a whole page into a modal surface.
Initial focus needs judgment. autofocus on the title is reasonable for a short editor. For a long or potentially destructive dialog, focus a heading or the least destructive control so opening it does not scroll important context away or invite an accidental action.
Style dialog::backdrop, not a hand-built overlay sibling. The top layer avoids common stacking-context fights. Keep the dialog within the viewport at high zoom and allow its content to scroll rather than clipping buttons below the screen.
Open this page and use only the keyboard. Focus should move into the dialog, Tab should stay within its modal interaction, and the rest of the board should not activate. Close it, reopen it, and confirm focus returns to Add task. If showModal() throws, check whether the same dialog is already open or is not connected to the document.
Lesson completed