Manage focus in modals

Move focus in, trap it, return it on close; use arrows inside groups.

From refactoring-ui, accessibility reference, “Focus Management”.

Delete by keyboard

Press Enter on Delete, Tab four times, then Escape.

Focus left aloneBad
acme-webProduction · 14 deployments
Danger zoneRemoves every deployment.

    dialog.hidden = false
    Focus managedGood
    acme-webProduction · 14 deployments
    Danger zoneRemoves every deployment.

      input.focus() → trap Tab → trigger.focus()

      One Tab stop per tab bar

      Tab through each bar to Save; use arrows in the good one.

      Every tab a Tab stopBad

      Settings for this section.

      6 stops
      Roving tabindexGood

      Settings for this section.

      1 stop

      Delete, keep your place

      Tab to a Delete button and press Enter three times.

      Focus droppedBad

      Files 5

        Focus: —

        row.remove()
        Focus to next rowGood

        Files 5

          Focus: —

          row.remove(); next.focus()

          Why it matters, pros and cons

          Why it matters

          For keyboard and screen-reader users, focus is the cursor. Lose it and they lose their place.

          Pros

          • No clicks behind the backdrop.
          • Closing or deleting keeps your place.
          • A tab bar costs one Tab stop.

          Cons

          • Hand-rolled traps break; prefer <dialog>.showModal().
          • Only trap true modals, not popovers or panels.
          • Never focus Delete first in a destructive confirm.