Skip to content

Instantly share code, notes, and snippets.

@HakurouKen
Created October 19, 2017 09:54
Show Gist options
  • Save HakurouKen/4b1dea6e135c56cf22c68af52324fd4d to your computer and use it in GitHub Desktop.
Save HakurouKen/4b1dea6e135c56cf22c68af52324fd4d to your computer and use it in GitHub Desktop.
A simple wrapper for event-listener to support ancient browsers.
let passiveSupported = false;
try {
// platform that doesn't support `addEventListener` or `Object.defineProperty`, obviously doesn't support `passive`.
let options = Object.defineProperty({}, 'passive', {
get: function() {
passiveSupported = true;
}
});
window.addEventListener('test-passive', null, options);
} catch (err) {}
export const add = document.addEventListener
? // modern browser
function(element, event, handler, options) {
const { capture = false, passive = true } =
typeof options === 'boolean' ? { capture: options } : options || {};
element.addEventListener(
event,
handler,
passiveSupported ? { capture, passive } : capture
);
}
: // IE 8-
function(element, event, handler) {
if (element && event && handler) {
element.attachEvent('on' + event, handler);
}
};
export const remove = document.removeEventListener
? function(element, event, handler) {
element.removeEventListener(event, handler);
}
: function(element, event, handler) {
element.detachEvent('on' + event, handler);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment