Skip to content

Instantly share code, notes, and snippets.

@robdodson
Last active September 16, 2023 18:09
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robdodson/7aabd62083d0bf66b20c431249379981 to your computer and use it in GitHub Desktop.
Save robdodson/7aabd62083d0bf66b20c431249379981 to your computer and use it in GitHub Desktop.
Differentiate between mouse and keyboard focus
// 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