mid · lesson 3 of 8

Focus management

Dialogs, route changes, and where focus goes next.

Sidhanshu Monga·1 min·
You’ll be able to
  1. Move focus into a dialog and back out again correctly
  2. Handle focus after client-side route changes
  3. Keep focus visible and in a logical order

Keyboard and screen reader users follow focus. When focus jumps somewhere unexpected, or disappears, they lose their place. Managing it well is invisible to mouse users and essential for everyone else.

Dialogs

The WAI-ARIA dialog pattern describes the expected behaviour:

  • On open, move focus into the dialog, usually to the first useful control
  • While open, Tab and Shift+Tab stay inside the dialog
  • Escape closes it
  • On close, return focus to the element that opened it

The native <dialog> element opened with showModal() handles much of this for you, and the inert attribute makes everything outside a modal unfocusable without manual focus traps.

Route changes

In a single-page app, clicking a link swaps the content but leaves focus on the link, which may no longer exist. Screen reader users hear nothing. After navigation, move focus to the new page's main heading or main region, and make sure the new page title is announced.

Removing and reordering

When the focused element disappears, for example a deleted list item, focus falls back to the document body. Move it somewhere sensible first: the next item, the previous one, or the list itself.

Visible and in order

Never remove focus outlines without a replacement. Use :focus-visible to show rings for keyboard users without showing them on every mouse click. Keep DOM order matching visual order, so Tab moves the way the eye expects.

Try it

Open every dialog, menu and drawer in your product using only the keyboard. Note where focus lands when each opens and closes. Fix the first one that leaves focus somewhere unexpected.

This lesson needs a hands-on exercise. The idea is sketched in issue #65. Build it and it ships here, with your name on it.
Key takeaways
01Focus should always be somewhere sensible and visible
02Dialogs take focus in and give it back on close
03Single-page navigation must move focus like a page load would