Skip to content

Instantly share code, notes, and snippets.

@zhibirc
Created September 13, 2021 06:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhibirc/db702941e13543545706335fa18e73ac to your computer and use it in GitHub Desktop.
Save zhibirc/db702941e13543545706335fa18e73ac to your computer and use it in GitHub Desktop.
Easy switch focus between two buttons
const buttons = [...document.getElementsByClassName('button')];
let focusedButtonIndex = 0;
buttons[focusedButtonIndex].focus();
window.addEventListener('keydown', event => {
if ( buttons.some(button => button === event.target) ) {
if ( event.code === 'ArrowDown' || event.code === 'ArrowUp' ) {
buttons[focusedButtonIndex ^= 1].focus();
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment