Last active
March 9, 2024 21:52
-
-
Save wuhhh/8c24f9615e84add68197063c7267619a to your computer and use it in GitHub Desktop.
Trap focus example (Svelte)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| export function trapFocus(node) { | |
| const previous = document.activeElement; | |
| function focusable() { | |
| return Array.from(node.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])')); | |
| } | |
| function handleKeydown(event) { | |
| if (event.key !== 'Tab') return; | |
| const current = document.activeElement; | |
| const elements = focusable(); | |
| const first = elements.at(0); | |
| const last = elements.at(-1) | |
| if (event.shiftKey && current === first) { | |
| last.focus(); | |
| event.preventDefault(); | |
| } | |
| if (!event.shiftKey && current === last) { | |
| first.focus(); | |
| event.preventDefault(); | |
| } | |
| } | |
| focusable()[0]?.focus(); | |
| node.addEventListener('keydown', handleKeydown); | |
| return { | |
| destroy() { | |
| node.removeEventListener('keydown', handleKeydown); | |
| previous?.focus(); | |
| } | |
| }; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment