focusTrap

Traps keyboard focus within an element. Essential for accessible modals and dialogs.

Usage

How It Works

  1. Finds all focusable elements within the container
  2. Intercepts Tab/Shift+Tab keydown events
  3. Wraps focus from last element to first (and vice versa)
  4. Optionally sets initial focus on mount

Options

enabled boolean true Whether focus trap is active
initialFocus string undefined CSS selector for initial focus target

Examples

Modal with Initial Focus

Dynamically Enable/Disable

Focusable Elements

The action considers these elements focusable:

  • a[href] - Links with href attribute
  • button:not([disabled]) - Enabled buttons
  • input:not([disabled]) - Enabled inputs
  • select:not([disabled]) - Enabled selects
  • textarea:not([disabled]) - Enabled textareas
  • [tabindex]:not([tabindex="-1"]) - Elements with positive tabindex

Accessibility Best Practices

  • Always use with modals - Required by WCAG 2.1
  • Set role="dialog" - Announce as dialog to screen readers
  • Add aria-modal="true" - Indicates modal nature
  • Combine with escapeKey - Allow keyboard dismissal
  • Return focus on close - Focus the trigger element after closing

Complete Accessible Modal