Skip to content
AITroveRead. Build. Understand.
Make this comfortable

HTML autofocus in a dialog: put focus on the next useful action

Last updated: 5 Oct 20267 min read
tutorial
IntermediateBy AITrove Editorial

Autofocus identifies the element that should receive focus when its containing dialog is shown.

When it earns its place

An operator opens a small correction panel containing a readonly asset code and an editable reason. Focusing the readonly code would make the next step unclear; the reason field is the useful starting point. Keep the dialog heading and context visible, then choose one autofocus target within that dialog. The opener must remain available so focus can return when the panel closes. For long or destructive dialogs, the safest first focus target may be the dialog or a non-destructive control instead of the confirm button.

html
<button type="button" id="open-correction">Correct inspection</button>
<dialog id="correction-panel" aria-labelledby="correction-heading">
  <h2 id="correction-heading">Correct inspection I-47</h2>
  <form action="/inspections/I-47/corrections" method="post">
    <label for="correction-reason">Reason for correction</label>
    <textarea id="correction-reason" name="reason" autofocus required></textarea>
    <button type="submit">Review correction</button>
  </form>
</dialog>
<script>
  const correctionPanel = document.querySelector("#correction-panel");
  document.querySelector("#open-correction").addEventListener("click", () => correctionPanel.showModal());
</script>

Browser boundary

Autofocus is a focus request, not a substitute for an accessible dialog name, visible labels, or backend validation. Only one element in the same autofocus scope should carry the attribute.

Cost and maintenance

Native dialog focus behavior avoids hand-written trapping code. The remaining cost is interaction testing across keyboard and assistive technology combinations, especially after conditional fields are added.

Common Mistakes

  • Do not autofocus the destructive confirmation by default.
  • Do not put multiple autofocus targets in one dialog.
  • Do not assume focus placement proves the form is accessible.

Connected lessons

html
accessibility
Storage details