Multiple event handlers in JavaScript
There is a very bad piece of advice going around the internet, that goes something like this:
if (el.addEventListener)
el.addEventListener('click', modifyText, false);
else if (el.attachEvent)
el.attachEvent('onclick', modifyText);
Mozilla/Safari/Opera support the addEventListener() function, which as you would expect, adds an event listener to the object. Listeners are executed in the order they are attached. Otherwise, the attachEvent() function is used, which comes with Internet Explorer. However, attachEvent() does not ensure the order listeners will be fired in. This can be a big problem when loading multiple scripts that depend on one-another.
There are three solutions:
Use the above code, and ensure that your listeners can be called in any order.
Write some messy code for Internet Explorer that works through a list of event listeners.
-
Just in case there is any question, the third option is the best. Let a library take care of this nonsense for you. But if you like pain, you can try something like the following:
var defer = function(torun) {
if (window.addEventListener)
window.addEventListener("load", torun, false);
else {
if (!defer.__onload) {
defer.__onload = [];
window.onload = function() {
for (var i=0; i < defer.__onload.length; i++)
defer.__onload[i]();
};
}
defer.__onload[defer.__onload.length] = torun;
}
}
This function will use addEventListener if it is available, otherwise it will create a hidden array of the items passed and register an onload function that executes the listeners. It is ugly, and needs some work if you want to generalise it for all objects and events, rather than just the window onload event. If you want that flexibility, use an already built library.