Created
October 19, 2017 09:54
-
-
Save HakurouKen/4b1dea6e135c56cf22c68af52324fd4d to your computer and use it in GitHub Desktop.
A simple wrapper for event-listener to support ancient browsers.
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
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