focusTrap
Traps keyboard focus within an element. Essential for accessible modals and dialogs.
Usage
How It Works
- Finds all focusable elements within the container
- Intercepts Tab/Shift+Tab keydown events
- Wraps focus from last element to first (and vice versa)
- Optionally sets initial focus on mount
Options
Examples
Modal with Initial Focus
Dynamically Enable/Disable
Focusable Elements
The action considers these elements focusable:
a[href]- Links with href attributebutton:not([disabled])- Enabled buttonsinput:not([disabled])- Enabled inputsselect:not([disabled])- Enabled selectstextarea: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