focus-trap is a vanilla JavaScript library designed to trap keyboard focus within a specified DOM node, essential for building accessible UI components like modals, dialogs, and sidebars. It ensures that users navigating with keyboard (Tab, Shift+Tab) or screen readers cannot escape the designated area, enhancing accessibility. The current stable version is 8.0.1, with releases occurring as needed for bug fixes (patch), new features (minor), and breaking changes (major). Key differentiators include its lightweight, framework-agnostic nature, robust handling of nested traps (pausing/unpausing), and its reliance on the well-maintained `tabbable` library for determining focusable elements. It handles initial focus, tabbing within the trap, blocking clicks outside, and restoring focus on deactivation. It explicitly supports modern desktop browsers and offers UMD builds for environments without bundlers.
npm install focus-trapVerified import paths — ran on the pinned version, not inferred.
Demonstrates creating, activating, and deactivating a focus trap for a modal dialog, including managing visibility and returning focus.
Review existing `onPostActivate()` implementations. If you relied on the previous, incorrect timing, you may need to adjust your logic or use `onActivate()` if you need a callback before focus is set.
Users and developers must enable 'Preferences > Advanced > Press Tab to highlight each item on a webpage' in Safari settings for focus traps to function correctly.
Avoid using `focus-trap` in projects requiring IE compatibility. Consider polyfills or alternative strategies for legacy browser support if absolutely necessary, but it's generally recommended to drop IE support.
Ensure that `<script src="https://unpkg.com/tabbable/dist/index.umd.js"></script>` is placed in your HTML *before* `<script src="https://unpkg.com/focus-trap/dist/focus-trap.umd.js"></script>`.
Ensure the DOM element passed to `createFocusTrap` exists and is a valid `HTMLElement`. Check for `null` or `undefined` returns from `document.getElementById` or `document.querySelector`.
For Safari, ensure the specific setting is enabled. Verify that your elements are natively tabbable or correctly marked with `tabindex`. Review the `tabbable` library documentation for details on what elements are considered tabbable. Also, check for CSS properties like `display: none` or `visibility: hidden` on the trap's container or its tabbable children.
Ensure the UMD script for `focus-trap` is properly loaded. When loaded via UMD, the exports are typically available under `window.FocusTrap`, so you would access `window.FocusTrap.createFocusTrap`.