Skip to content

Instantly share code, notes, and snippets.

@kara-ryli
Created October 16, 2015 20:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kara-ryli/50d0e68451ec2fb1ce7b to your computer and use it in GitHub Desktop.
Save kara-ryli/50d0e68451ec2fb1ce7b to your computer and use it in GitHub Desktop.
Dead-simple event handling polyfills. Based largely on http://youmightnotneedjquery.com/
/**
* Dead-simple event handling polyfills. Based largely on
* http://youmightnotneedjquery.com/
*/
/**
* IE-safe removeEventListener polyfill. Not exported to avoid bugs
* caused by wrapping the event handler in IE8.
*
* @param {Window|Document|HTMLElement} el Element to listen on
* @param {String} eventName The event to register
* @param {Function} handler Event handler
*/
function off(el, eventName, handler) {
if (el.removeEventListener) {
el.removeEventListener(eventName, handler);
} else {
el.detachEvent("on" + eventName, handler);
}
}
/**
* IE8-safe addEventListener polyfill
*
* @param {Window|Document|HTMLElement} el Element to listen on
* @param {String} eventName The event to register
* @param {Function} handler Event handler
* @return {Function} Detaches the handler when called
*/
function on(el, eventName, handler) {
var h;
if (el.addEventListener) {
h = handler;
el.addEventListener(eventName, handler);
} else {
h = function () {
handler.call(el, window.event);
};
el.attachEvent("on" + eventName, h);
}
return function detach() {
if (el) {
off(el, eventName, h);
el = h = null;
}
};
}
exports.on = on;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment