Skip to content

Instantly share code, notes, and snippets.

@wuhhh
Last active March 9, 2024 21:52
Show Gist options
  • Save wuhhh/8c24f9615e84add68197063c7267619a to your computer and use it in GitHub Desktop.
Save wuhhh/8c24f9615e84add68197063c7267619a to your computer and use it in GitHub Desktop.
Trap focus example (Svelte)
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