Skip to content

Instantly share code, notes, and snippets.

@dciccale
Last active December 16, 2015 06:49
Show Gist options
  • Save dciccale/5394590 to your computer and use it in GitHub Desktop.
Save dciccale/5394590 to your computer and use it in GitHub Desktop.
Cross-browser addEvent function done with 81 bytes of JavaScript

addEvent

Cross-browser function to add events on DOM elements.

/**
* @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);
}
};
function(a,b,c){try{a.addEventListener(b,c,!1)}catch(d){a.attachEvent('on'+b,c)}}
<!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>
@nikitakuz
Copy link

You got a typo on line 8. "callback" is mispelled with only one L: "calback"

@dciccale
Copy link
Author

Fixed, thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment