Last active
September 16, 2023 18:09
-
-
Save robdodson/7aabd62083d0bf66b20c431249379981 to your computer and use it in GitHub Desktop.
Differentiate between mouse and keyboard focus
This file contains 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
// Handlers managed by the addFocusStates and removeFocusStates methods. | |
var onMouseDown = function() { | |
this.classList.add('pressed'); | |
}; | |
var onMouseUp = function() { | |
this.classList.remove('pressed'); | |
}; | |
var onFocus = function() { | |
// Only render the "focused" state if the element gains focus due to | |
// keyboard navigation. | |
if (!this.classList.contains('pressed')) { | |
this.classList.add('focused'); | |
} | |
}; | |
var onBlur = function() { | |
this.classList.remove('focused'); | |
}; | |
// Elements passed to this method will receive classes reflecting the focus | |
// and pressed states. | |
function addFocusStates(selector) { | |
var nodes = document.querySelectorAll(selector); | |
Array.prototype.forEach.call(nodes, function(el) { | |
el.addEventListener('mousedown', onMouseDown); | |
el.addEventListener('mouseup', onMouseUp); | |
el.addEventListener('focus', onFocus); | |
el.addEventListener('blur', onBlur); | |
}); | |
} | |
// Cleanup method for elements with managed focus states | |
function removeFocusStates(selector) { | |
var nodes = document.querySelectorAll(selector); | |
Array.prototype.forEach.call(nodes, function(el) { | |
el.removeEventListener('mousedown', onMouseDown); | |
el.removeEventListener('mouseup', onMouseUp); | |
el.removeEventListener('focus', onFocus); | |
el.removeEventListener('blur', onBlur); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment