Skip to content

Instantly share code, notes, and snippets.

@tadeaspetak
Last active February 22, 2022 12:35
Show Gist options
  • Save tadeaspetak/83117b16ccca0856b09e73eb9b61fe55 to your computer and use it in GitHub Desktop.
Save tadeaspetak/83117b16ccca0856b09e73eb9b61fe55 to your computer and use it in GitHub Desktop.
export const nextFocusable = (elements: HTMLElement[], forward = true) => {
const currentIndex = elements.findIndex((e) => e === document.activeElement);
let nextIndex = 0;
if (currentIndex > -1) {
if (forward) {
nextIndex = currentIndex < elements.length - 1 ? currentIndex + 1 : 0;
} else {
nextIndex = currentIndex > 0 ? currentIndex - 1 : elements.length - 1;
}
}
elements[nextIndex]?.focus();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment