Created
July 22, 2018 06:21
-
-
Save nickav/2f0c32ce83b2fa938f9d7b5315138d7c to your computer and use it in GitHub Desktop.
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
/*! track-focus v 1.0.0 | Author: Jeremy Fields [[email protected]], 2015 | License: MIT */ | |
// inspired by: http://irama.org/pkg/keyboard-focus-0.3/jquery.keyboard-focus.js | |
/** | |
* Tracks an element is focused via the mouse or keyboard. On mouse focus, adds | |
* the mouseClass to the element. | |
* | |
* Adapted from: https://github.com/ten1seven/track-focus/blob/master/src/javascripts/track-focus.js | |
*/ | |
/* | |
&.focus--mouse { | |
a, | |
button { | |
outline: 0 !important; | |
} | |
} | |
*/ | |
export default function trackFocus(el, mouseClass = 'focus--mouse') { | |
let usingMouse; | |
function preFocus(event) { | |
usingMouse = event.type === 'mousedown'; | |
} | |
function addFocus(event) { | |
if (usingMouse) el.classList.add(mouseClass); | |
} | |
function removeFocus(event) { | |
el.classList.remove(mouseClass); | |
} | |
function bindEvents() { | |
el.addEventListener('keydown', preFocus); | |
el.addEventListener('mousedown', preFocus); | |
el.addEventListener('focusin', addFocus); | |
el.addEventListener('focusout', removeFocus); | |
} | |
function unbindEvents() { | |
el.removeEventListener('keydown', preFocus); | |
el.removeEventListener('mousedown', preFocus); | |
el.removeEventListener('focusin', addFocus); | |
el.removeEventListener('focusout', removeFocus); | |
} | |
bindEvents(); | |
return unbindEvents; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment