Last active
May 18, 2018 12:55
-
-
Save elhardoum/e0d966fcbf9e18219c2f62ef18371ceb to your computer and use it in GitHub Desktop.
Attach multiple events (click, load, etc) to a DOM element
This file contains hidden or 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(){ | |
'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