Last active
March 9, 2024 21:52
-
-
Save wuhhh/8c24f9615e84add68197063c7267619a to your computer and use it in GitHub Desktop.
Revisions
-
Huw Roberts revised this gist
Mar 9, 2024 . No changes.There are no files selected for viewing
-
Huw Roberts revised this gist
Mar 9, 2024 . 1 changed file with 8 additions and 1 deletion.There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -27,5 +27,12 @@ export function trapFocus(node) { focusable()[0]?.focus(); node.addEventListener('keydown', handleKeydown); return { destroy() { node.removeEventListener('keydown', handleKeydown); previous?.focus(); } }; } -
Huw Roberts created this gist
Mar 9, 2024 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,31 @@ 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(); // TODO finish writing the action }