Course contentsShow
← Web Development
Lesson 1050 of 2,98219. Keyboard Navigation and FocusFree lesson

Focus Trapping in Modal Dialogs

Implementing keyboard traps to cycle focus within modals and preventing focus from leaving the dialog.

Focus Trapping in Modal Dialogs

You'll learn how to keep keyboard focus inside a modal dialog and prevent users from accidentally navigating to background content.

What is Focus Trapping?

When a modal dialog opens, users (especially keyboard-only users) shouldn't be able to tab through the underlying page content. Focus trapping creates an invisible "fence" around the modal, cycling keyboard focus among only the interactive elements inside that dialog.

Think of it like a TV remote that only works in the room you're currently in—you can switch between all the channels available in that room, but you can't access channels from other rooms until you leave.

Why Focus Matters in Modals

Without focus trapping:

  • Pressing Tab repeatedly might move focus to elements hidden behind the modal
  • Users lose track of where they are in the interface
  • Screen reader users might interact with the wrong content
  • Keyboard navigation becomes confusing and broken

The Core Pattern

Focus trapping involves:

  1. Finding all focusable elements inside the modal (buttons, links, inputs, elements with tabindex="0")
  2. Setting initial focus when the modal opens (often the close button or first input)
  3. Listening for Tab keypresses to detect when focus tries to leave
  4. Wrapping focus from the last element back to the first (and vice versa with Shift+Tab)
  5. Restoring focus to the triggering element when the modal closes

Using tabindex="-1" (from lesson 1046) helps you programmatically focus non-interactive elements like the modal container itself, while tabindex="0" ensures custom interactive elements participate in the tab sequence.

Key Takeaway: Focus trapping confines keyboard navigation within a modal dialog by cycling focus among its interactive elements, preventing access to background content until the modal is dismissed.