[thelist] looking for HACK for events

Simon Willison cs1spw at bath.ac.uk
Wed Oct 8 18:06:56 CDT 2003

jsWalter wrote:
> Anyone have any tricks for attaching more than one method to a single event?

I always use the following function - I think it origianlly came from 
www.scottandrew.com, but I've seen it used all over the place:

function addEvent(obj, evType, fn){
   if (obj.addEventListener){
     obj.addEventListener(evType, fn, true);
     return true;
   } else if (obj.attachEvent){
     var r = obj.attachEvent("on"+evType, fn);
     return r;
   } else {
     return false;

You can then use it to attach specific functions to events on an object 
- for example:

addEvent(document.getElementById('myDiv'), 'click', someFunction);

A neat alternative I saw the other day was to wrap multiple methods in 
an anonymous function - for example:

window.onload = function() {

Hope that helps,

Simon Willison

More information about the thelist mailing list