Skip to content

Instantly share code, notes, and snippets.

@Freekbron
Last active February 4, 2019 15:10
Show Gist options
  • Save Freekbron/11a2ab8fb8d640d8ed735a1031a9cb8f to your computer and use it in GitHub Desktop.
Save Freekbron/11a2ab8fb8d640d8ed735a1031a9cb8f to your computer and use it in GitHub Desktop.
Keyfocus styling
const body = document.body;
const tabFocusClass = 'is-keyfocus';
const CODE_TAB = 9;
let focusState = false;
/**
* Handle logic, when onTabKeyPress fired at first.
* Then it changes state.
*/
function onFocusInHandler() {
focusState = true;
body.classList.add(tabFocusClass);
body.removeEventListener('focusin', onFocusInHandler);
}
/**
* Handle logic to remove state after onTabKeyPress to normal.
*/
function onClickHandler() {
focusState = false;
body.classList.remove(tabFocusClass);
body.removeEventListener('click', onClickHandler);
}
/**
* Handle logic to check if tab key is pressed
*/
function onKeyHandler(event) {
if (event.which === CODE_TAB && !focusState) {
body.addEventListener('focusin', onFocusInHandler);
body.addEventListener('click', onClickHandler);
}
}
/**
* Tab key onKeypress handler. Apply main logic:
* - call differ actions onTabKeyPress and onClick
*/
function smartKeyboardFocus() {
['keydown', 'keypress'].forEach(function(e) {
document.addEventListener(e, function(event) {
onKeyHandler(event);
});
});
}
smartKeyboardFocus();
body:not(.is-keyfocus) *:focus {
outline-style: none;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment