Skip to content

Instantly share code, notes, and snippets.

@Smona
Created December 6, 2019 19:37
Show Gist options
  • Save Smona/93722bb482dd5d88d50c5cb565dde0fe to your computer and use it in GitHub Desktop.
Save Smona/93722bb482dd5d88d50c5cb565dde0fe to your computer and use it in GitHub Desktop.
Replicates tabbing behavior with a function
/**
* 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