{"slug":"focus-trap","title":"Focus Trap","description":"Using the Focus Trap utility in your project.","contentType":"utilities","content":"The focus trap utility is used to trap focus within a DOM element, preventing\nusers from tabbing outside of a specific region.\n\n<Resources pkg=\"@zag-js/focus-trap\" />\n\n**Features**\n\n- Handles edge cases like hidden elements\n- Works with shadow DOM\n- Supports nested focus traps\n- Follows ARIA-controlled elements\n\n## Installation\n\n```bash\nnpm install @zag-js/focus-trap\n```\n\n## Usage\n\n```js\nimport { trapFocus } from \"@zag-js/focus-trap\"\n\n// Trap focus within an element\nconst restore = trapFocus(element, {\n  initialFocus: \"#first-input\",\n  returnFocusOnDeactivate: true,\n})\n\n// Later, release the trap\nrestore()\n```\n\n### Framework Usage\n\n<CodeSnippet id=\"focus-trap/usage.mdx\" />\n\n## API Reference\n\n### trapFocus\n\n```ts\nfunction trapFocus(\n  element: HTMLElement | null | (() => HTMLElement | null),\n  options?: TrapFocusOptions,\n): () => void\n```\n\nCreates a focus trap for the specified element.\n\n**Parameters:**\n\n- `element` - The container element to trap focus within, or a function that\n  returns the element\n- `options` - Configuration options for the focus trap\n\n**Returns:** A cleanup function that deactivates the focus trap when called.\n\n### Options\n\n| Property                   | Description                                      |\n| -------------------------- | ------------------------------------------------ |\n| `initialFocus`             | Element to receive focus on activation           |\n| `fallbackFocus`            | Fallback element if no tabbable elements found   |\n| `returnFocusOnDeactivate`  | Return focus to previous element on deactivation |\n| `escapeDeactivates`        | Allow ESC key to deactivate trap                 |\n| `clickOutsideDeactivates`  | Deactivate trap on outside click                 |\n| `allowOutsideClick`        | Allow outside clicks without deactivating        |\n| `preventScroll`            | Prevent scrolling when focusing                  |\n| `delayInitialFocus`        | Delay initial focus to prevent event capture     |\n| `followControlledElements` | Include ARIA-controlled elements                 |\n| `getShadowRoot`            | Enable shadow DOM traversal                      |\n| `isKeyForward`             | Custom forward navigation key                    |\n| `isKeyBackward`            | Custom backward navigation key                   |\n| `onActivate`               | Called before activation                         |\n| `onPostActivate`           | Called after activation                          |\n| `onDeactivate`             | Called before deactivation                       |\n| `onPostDeactivate`         | Called after deactivation                        |","package":"@zag-js/focus-trap","editUrl":"https://github.com/chakra-ui/zag/edit/main/website/data/utilities/focus-trap.mdx"}