🎯 Focus Trap Generator

Quickly generate modal focus trap code ensuring Tab key cycles within dialogs, WCAG-compliant

Zero Dependencies·Works Offline

⚙️ Configuration

📄 Generated Code

What can Focus Trap Generator do?

Focus Trap Generator is a free online tool that helps developers quickly generate modal focus management code. A focus trap ensures the Tab key cycles within a dialog, preventing it from reaching background content - a requirement of WCAG accessibility standards. This tool supports both vanilla JavaScript and React Hook code styles with configurable options for Esc close, focus restoration, and more.

Core Features

Use Cases

Case 1: Modal Dialogs

Add focus traps to modals ensuring keyboard users can only operate within the dialog, preventing Tab from reaching the background.

Case 2: Drawer Panels

When a side drawer opens, focus should be trapped within it and restored to the trigger button on close.

Case 3: Full-screen Overlays

Full-screen overlays (image viewers, onboarding flows) need focus traps to prevent accidental background interaction.

FAQ

What is a focus trap?
A focus trap ensures Tab key focus cycles within a modal, preventing it from reaching background content. Required by WCAG accessibility standards.
Why do modals need focus traps?
Without a focus trap, Tab moves to background elements, causing confusion. WCAG 2.4.3 requires focus to cycle within the modal.
Which frameworks are supported?
Pure JavaScript code works in any framework. React Hook version also available.
Is data uploaded?
No. This tool runs entirely in your browser. No data is uploaded to any server.

Focus Trap Generator · Client-side processing · Data never uploaded to servers

Feedback: dexshuang@google.com

✅ Copied to clipboard
`;} function generateUsageReact(){return `import { useFocusTrap } from './useFocusTrap';\n\nfunction Modal({ isOpen, onClose }) {\n const trapRef = useFocusTrap({\n escClose: true,\n restoreFocus: true,\n onClose\n });\n\n if (!isOpen) return null;\n\n return (\n
\n e.stopPropagation()}\n >\n \n

Tab key will cycle within this container

\n \n \n
\n \n );\n}`;} function copyCode(){const text=document.getElementById('code-text').textContent;navigator.clipboard.writeText(text).then(()=>{const t=document.getElementById('copy-toast');t.classList.add('show');setTimeout(()=>t.classList.remove('show'),2000);});} function resetForm(){document.getElementById('code-style').value='vanilla';document.getElementById('container-selector').value='.modal';document.getElementById('initial-focus').value='[autofocus]';document.getElementById('esc-close').checked=true;document.getElementById('restore-focus').checked=true;updateCode();} function toggleFaq(el){el.parentElement.classList.toggle('open');} updateCode();