← Lessons

quiz vs the machine

Gold1390

Frontend

Focus Management and Keyboard Traps

Guide keyboard focus through modals without stranding the user.

6 min read · core · beat Gold to climb

Why focus matters

Keyboard and screen reader users navigate by focus. When a modal opens, focus should move into it, stay within it, and return sensibly when it closes. Mishandling this strands users or hides content.

Managing focus for a dialog

  • On open, move focus to the dialog or its first interactive element.
  • Trap focus so Tab and Shift Tab cycle within the dialog, not behind it.
  • On close, return focus to the element that opened the dialog.

Good trap versus bad trap

A deliberate trap inside a modal is correct. A keyboard trap that the user cannot escape, with no way to Tab out and no Escape, is an accessibility failure. Always provide an exit.

Helpers

  • The inert attribute disables interaction and focus for background content.
  • The native dialog element handles much of this when used with showModal.

Key idea

Good focus management moves focus into a dialog, cycles within it, and restores it on close, while avoiding inescapable keyboard traps.

Check yourself

Answer to earn rating on the learn ladder.

1. When a modal closes, where should focus go?

2. What makes a focus trap an accessibility failure?