Created
February 20, 2014 17:20
-
-
Save glynthomas/9118814 to your computer and use it in GitHub Desktop.
Cross Browser Add and Remove Event Listeners idea / demo
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
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