Cross-browser function to add events on DOM elements.
Last active
December 16, 2015 06:49
-
-
Save dciccale/5394590 to your computer and use it in GitHub Desktop.
Cross-browser addEvent function done with 81 bytes of JavaScript
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
/** | |
* @param element The element to add the event | |
* @param type Event type (i.e. 'click') | |
* @param callback Function to execute when event is triggered | |
*/ | |
function (element, type, callback) { | |
try { | |
element.addEventListener(type, callback, false); | |
} catch (e) { | |
element.attachEvent('on' + type, callback); | |
} | |
}; |
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
function(a,b,c){try{a.addEventListener(b,c,!1)}catch(d){a.attachEvent('on'+b,c)}} |
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
<!doctype html> | |
<title>Demo</title> | |
<span id="btn">Button</span> | |
<script> | |
var addEvent = function(a,b,c){try{a.addEventListener(b,c,!1)}catch(d){a.attachEvent('on'+b,c)}}; | |
var element = document.getElementById('btn'); | |
addEvent(element, 'click', function () { | |
alert('Button clicked!'); | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You got a typo on line 8. "callback" is mispelled with only one L: "calback"