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

Focus Trap Implementation

Building a robust focus trap that cycles through focusable elements and prevents escape with Tab key.

Focus Trap Implementation

You'll learn how to keep keyboard focus cycling within a specific component, preventing users from tabbing out accidentally.

When you open a modal dialog or drawer, keyboard focus should stay "trapped" inside until the user intentionally closes it. Without this, pressing Tab repeatedly would move focus behind the modal to the underlying page—confusing for everyone, especially screen reader users.

Think of it like a velvet rope at a museum exhibit: visitors can explore freely within the roped area, but they can't accidentally wander into off-limits sections. When they're done, they exit through the proper door.

How It Works

A focus trap monitors keyboard events and redirects focus when it reaches the boundaries:

On first open:

  • Find all focusable elements inside the container (button, a[href], input, select, textarea, [tabindex]:not([tabindex="-1"]))
  • Store the element that was focused before opening (to return to later)
  • Move focus to the first interactive element inside

During Tab/Shift+Tab:

  • When focus reaches the last element and user presses Tab → move to first element
  • When focus is on first element and user presses Shift+Tab → move to last element

On close:

  • Return focus to the stored element from before the trap opened

Key Implementation Detail

You must handle both Tab directions. Listen for keydown, check if event.key === 'Tab', then check event.shiftKey to determine direction. Use event.preventDefault() when cycling, then manually call .focus() on the target element.

Key Takeaway: A focus trap creates a circular tab order within a container by detecting when focus reaches the first or last focusable element, then redirecting it to the opposite boundary—ensuring keyboard users stay within the intended context.