Skip to content

Instantly share code, notes, and snippets.

@THEtheChad
Created May 15, 2019 15:05
Show Gist options
  • Save THEtheChad/d115f1d1914bb9ff7863a4291af51504 to your computer and use it in GitHub Desktop.
Save THEtheChad/d115f1d1914bb9ff7863a4291af51504 to your computer and use it in GitHub Desktop.
Cross browser event listener.
function removeHandler(){
this.element.removeEventListener(this.event, this.handler)
}
function detachHandler(){
this.element.detachEvent('on' + this.event, this.handler)
}
function addEvent(ele, evt, fn){
if(ele.addEventListener){
function listenHandler(e){
var ret = fn.apply(this, arguments);
if(ret === false){
e.stopPropagation();
e.preventDefault();
}
return(ret);
}
ele.addEventListener(evt, listenHandler, false);
return {
element: ele,
handler: listenHandler,
event: evt,
remove: removeHandler
}
} else {
function attachHandler(){
var ret = fn.call(ele, window.event);
if(ret === false){
window.event.returnValue = false;
window.event.cancelBubble = true;
}
return(ret);
}
ele.attachEvent('on' + evt, attachHandler)
return {
element: ele,
handler: attachHandler,
event: evt,
remove: detachHandler
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment