Created
December 6, 2019 19:37
-
-
Save Smona/93722bb482dd5d88d50c5cb565dde0fe to your computer and use it in GitHub Desktop.
Replicates tabbing behavior with a function
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
/** | |
* Moves focus to the next focusable element on the page, similar to pressing <Tab> | |
* | |
* Does not currently honor tab-indexes | |
*/ | |
export function advanceFocus() { | |
//Isolate the node that we're after | |
const currentNode = document.activeElement; | |
//find all tab-able elements | |
const allElements: NodeListOf<Focusable> = document.querySelectorAll( | |
"input, button, a, area, object, select, textarea" | |
); | |
//Find the current tab index. | |
const currentIndex = [...Array.from(allElements)].findIndex(el => | |
currentNode.isEqualNode(el) | |
); | |
//focus the following element | |
const nextIndex = (currentIndex + 1) % allElements.length; | |
allElements[nextIndex].focus(); | |
} | |
type Focusable = | |
| HTMLInputElement | |
| HTMLButtonElement | |
| HTMLAnchorElement | |
| HTMLAreaElement | |
| HTMLObjectElement | |
| HTMLTextAreaElement; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment