Last active
February 4, 2019 15:10
-
-
Save Freekbron/11a2ab8fb8d640d8ed735a1031a9cb8f to your computer and use it in GitHub Desktop.
Keyfocus styling
This file contains hidden or 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
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(); |
This file contains hidden or 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
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