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 job. The dialog element gives you a real browser primitive instead of a positioned div that only looks modal.

Call showModal() to put the dialog in the top layer. The browser makes the rest of the page inert, exposes modal semantics, and lets you style ::backdrop. A plain open attribute or show() opens a non-modal dialog. That does not give you 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>

Click Add task and focus moves into the dialog. Tab stays inside the modal interaction. The board behind it should not activate.

Give the dialog an accessible name. A visible heading inside it is usually enough. Use aria-labelledby when you need an explicit link to that heading. Keep one job per dialog. Do not move a whole page into a modal surface.

Initial focus needs judgment. autofocus on the title field fits a short editor. For a long or destructive dialog, focus a heading or the safest control so opening it does not scroll important context away or invite a mis-click.

Style dialog::backdrop, not a hand-built overlay sibling. The top layer avoids most z-index fights. Keep the dialog inside the viewport at high zoom and let long content scroll instead of clipping buttons off screen.

Try this with keyboard only: open the dialog, Tab inside it, close it, and confirm focus returns to Add task. If showModal() throws, check whether the same dialog is already open or not connected to the document.

Lesson completed