Cross-browser function for adding an event listener
Here is a function that should work in virtually every browser, even really old ones. Of course, it is only useful, if you don’t use jQuery. Because, if you do, a far better way is to just call .on()
or .bind()
or .delegate()
or .live()
or whatever you want, and let jQuery do all the dirty work.
Function code:
/** * Adds event handler; works for all browsers, including old IE versions. * * @param event Event name (string) to attach. * @param thefunction Function executed upon attached event fire (callback). */ function addListener(event, thefunction) { if(window.addEventListener) { //All browsers, except IE before version 9. window.addEventListener(event, thefunction, false); } else if(window.attachEvent) { //IE before version 9. event = (event == 'DOMContentLoaded') ? 'onreadystatechange' : "on" + event; window.attachEvent(event, thefunction); } else { /** * Code for really old ones -- like NS4 or IE5Mac, which * neither support attachEvent nor addEventListener * * This code is copyright 2003 by Gavin Kistner, !@phrogz.net * It is covered under the license viewable at http://phrogz.net/JS/_ReuseLicense.txt * * More info: http://phrogz.net/JS/AttachEvent_js.txt */ if(!window.myEvents) window.myEvents = {}; if(!window.myEvents[event]) window.myEvents[event] = []; var events = window.myEvents[event]; events[events.length] = thefunction; window['on' + event] = function() { if(!window || !window.myEvents || !window.myEvents[event]) return; var events = window.myEvents[event]; for(var i = 0, len = events.length; i<len; i++) events[i](); }; } }
Because I don’t have access to those “really old ones”, I cannot test and guarantee, that it will work there. Example used here comes from 2003, so it is itself “really old one”! :]