Skip to content

Instantly share code, notes, and snippets.

@elhardoum
Last active May 18, 2018 12:55
Show Gist options
  • Save elhardoum/e0d966fcbf9e18219c2f62ef18371ceb to your computer and use it in GitHub Desktop.
Save elhardoum/e0d966fcbf9e18219c2f62ef18371ceb to your computer and use it in GitHub Desktop.
Attach multiple events (click, load, etc) to a DOM element
(function(){
'use strict';
Object.prototype.attachDomEvent = function(eventName, callback)
{
eventName = eventName.replace(/^on/g, '');
if ( window.addEventListener ) {
this.addEventListener(eventName, callback, false);
} else if ( window.attachEvent ) {
this.attachEvent('on'+eventName, callback);
} else {
var registered = this['on' + eventName];
this['on' + eventName] = registered ? function(e) {
registered(e);
callback(e);
} : callback;
}
return this;
}
})();
// examples
window.attachDomEvent('onload', function(){
alert('Loaded!')
});
document.getElementById('button').attachDomEvent('onclick', function(){
alert('Clicked!')
}).attachDomEvent('onclick', function(){
alert('Did I say clicked?')
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment