Skip to content

Instantly share code, notes, and snippets.

@hyunbinseo
Created January 15, 2023 14:07
Show Gist options
  • Save hyunbinseo/c9bb1a6b765718f66fbcbb7a89f10b6f to your computer and use it in GitHub Desktop.
Save hyunbinseo/c9bb1a6b765718f66fbcbb7a89f10b6f to your computer and use it in GitHub Desktop.
Lock focus on modal elements, TypeScript
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