Skip to the page

Keyboard, focus and widgets · mid

Focus management: modals, route changes and dynamic content

When the UI changes without a page load, you must move focus on purpose: into a dialog when it opens (and keep it there), back to the trigger when it closes, to the new page's heading after a client-side route change, and somewhere sensible when the focused element is removed.

The notes

What you must know

  • Modal dialog (APG): on open move focus inside (first focusable element, or the title with tabindex=-1 for long content, or the least destructive button); Tab and Shift+Tab cycle inside; Escape closes; on close return focus to the element that opened it.
  • Roles: role=dialog with aria-modal="true" and aria-labelledby pointing to the visible title (aria-describedby optional).
  • Native <dialog> with showModal() puts the dialog in the top layer, makes the rest of the page inert, handles Escape and moves focus inside; still check that focus returns to the trigger in your target browsers.
  • The inert attribute (Baseline 2023) disables a whole region (no focus, no clicks, hidden from assistive tech): the modern way to block the background.
  • SPA route change: update document.title, move focus to the new page's h1 (tabindex=-1) or main region, and/or announce the page with a live region. Next.js App Router includes a route announcer.
  • Deleting the focused item (removing a cart row): move focus to the next row, the previous one, or the list heading, never leave it on <body>.
  • Bottom sheets and drawers on mobile web follow the same rules as dialogs.

The red pen

Common traps: mistake → fix

  • Mistake: "Opening the modal is enough, focus will follow"

    Fix: focus stays on the page behind; keyboard and screen-reader users are lost.

  • Mistake: "aria-modal='true' blocks the background"

    Fix: it only tells assistive tech; you still trap focus or use inert / showModal.

  • Mistake: "Route changes in SPAs are announced automatically"

    Fix: without a page load, screen readers say nothing unless you move focus or announce.

Easy to hard

Questions interviewers ask, easy to hard

  1. How do you manage focus when a modal opens and closes?
  2. Native <dialog> vs a custom modal with a focus trap: trade-offs?
  3. What should happen to focus on a client-side route change?
  4. Build a global BottomSheet that can be opened from anywhere: what are the accessibility requirements?

Practise

Practise with these questions

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview