Skip to content

Instantly share code, notes, and snippets.

@glynthomas
Created February 20, 2014 17:20
Show Gist options
  • Save glynthomas/9118814 to your computer and use it in GitHub Desktop.
Save glynthomas/9118814 to your computer and use it in GitHub Desktop.
Cross Browser Add and Remove Event Listeners idea / demo
var addEvent, removeEvent;
if ( window.addEventListener ) {
addEvent = function(obj, type, fn ) {
obj.addEventListener(type, fn, false );
}
removeEvent = function(obj, type, fn ) {
obj.removeEventListener(type, fn, false );
}
} else if (document.attachEvent) {
addEvent = function(obj, type, fn ) {
var eProp = type + fn;
obj['e'+eProp] = fn;
obj[eProp] = function(){obj['e'+eProp]( window.event );}
obj.attachEvent( 'on'+type, obj[eProp] );
}
removeEvent = function(obj, type, fn ) {
var eProp = type + fn;
obj.detachEvent( 'on'+type, obj[eProp] );
obj[eProp] = null;
obj["e"+eProp] = null;
}
}
This code owes a lot to John Resig,
example of the way you would write your call to actually use it ...
var lnk = document.getElementById('ex');
addEvent(lnk, 'click', function(event) {
alert(this.nodeName);
alert(event);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment