Skip to content

Instantly share code, notes, and snippets.

@tschiela
Created November 23, 2015 08:46
Show Gist options
  • Save tschiela/250bc157966679577376 to your computer and use it in GitHub Desktop.
Save tschiela/250bc157966679577376 to your computer and use it in GitHub Desktop.
fix event types triggered by browser on keyevents (e.g. browser send key and click event if user use SPACE or ENTER on a button or form element)
'use strict';
/**
* @param {Function} callback
* @return {Function}
*/
var fixEventType = function (callback) {
var eventFired = false,
eventStack = [];
return function () {
var self = this;
eventStack.push(arguments[0]);
// check if an event is fired within 100ms
if (!eventFired) {
eventFired = true;
setTimeout(function () {
var keyEventIndex = -1,
clickEventIndex = -1,
i,
eventStackLen = eventStack.length;
eventFired = false;
// check which events was triggered
for (i = 0; i < eventStackLen; i += 1) {
if (eventStack[i].type === 'keyup') {
keyEventIndex = i;
} else if (eventStack[i].type === 'click') {
clickEventIndex = i;
}
}
// if click and key event was triggered only let pass key event
if (keyEventIndex > -1 && clickEventIndex > -1) {
callback.call(self, eventStack[keyEventIndex]);
// if multiple key events was triggered only let pass last key event
} else if (keyEventIndex > -1) {
callback.call(self, eventStack[keyEventIndex]);
// if only mouse even was triggered let pass last mouse event
} else if (clickEventIndex > -1) {
callback.call(self, eventStack[clickEventIndex]);
}
eventStack = [];
}, 100);
}
};
};
/**
* @type {Function}
*/
var someEventHandler = fixEventType(function (event) {
console.log(event.type);
});
/**
* problem: browser will trigger a key and a click event, if user use keyboard (SPACE or ENTER) to interact with buttons / form elements / links
* solution: fixEventType only let pass key event to the wrapped event handler
*/
document.getElementById('some-button').addEventListener('keyup', someEventHandler);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment