Created
January 15, 2023 14:07
-
-
Save hyunbinseo/c9bb1a6b765718f66fbcbb7a89f10b6f to your computer and use it in GitHub Desktop.
Lock focus on modal elements, TypeScript
This file contains 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
const tabIndexGuard = (el: Element): el is HTMLElement => (el as HTMLElement).tabIndex >= 0; | |
// Based on https://svelte.dev/examples/modal | |
export const focusLock = (e: KeyboardEvent, el: HTMLElement) => { | |
if (e.key === 'Tab') { | |
// trap focus | |
const nodes = el.querySelectorAll('*'); | |
const tabbable = Array.from(nodes).filter(tabIndexGuard); | |
let index = tabbable.indexOf(document.activeElement as HTMLElement); | |
if (index === -1 && e.shiftKey) index = 0; | |
index += tabbable.length + (e.shiftKey ? -1 : 1); | |
index %= tabbable.length; | |
tabbable[index].focus(); | |
e.preventDefault(); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment