addEvent winner announced

If any of you have tried unobtrusive scripting through DOM, then you will most likely be aware of the complexities involved with adding events consistantly to objects (including the window itself).

A few weeks back, PPK released a short article decrying the current state of Scott Andrew’s addEvent() function, a common function which people use to attach events in cross-browser scripts.

I use a variant of Scott’s function myself, so was interested to see what would develop from this.

Accordingly, announced a competition to come up with a new function to replace the aging one.

The winner has been announced. The winning entry is a pair of functions by John Resig.

So, now that the functions are available, it’s time for everyone and their dogs to steal it (yoink! I now have a copy)! Well done, John.

Here are the functions:

function addEvent( obj, type, fn ) {
 if ( obj.attachEvent ) {
  obj['e'+type+fn] = fn;
  obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
  obj.attachEvent( 'on'+type, obj[type+fn] );
 } else
 obj.addEventListener( type, fn, false );
function removeEvent( obj, type, fn ) {
 if ( obj.detachEvent ) {
 obj.detachEvent( 'on'+type, obj[type+fn] );
 obj[type+fn] = null;
} else
 obj.removeEventListener( type, fn, false );

Very interesting code. I’ll need to set aside a few minutes later to absorb how it works. In the meantime, here is a compressed version (with ; added (see here) at end of =function() bit):

function addEvent(a,b,c){if(a.attachEvent){a['e'+b+c]=c;a[b+c]=function(){a['e'+b+c](window.event);}a.attachEvent('on'+b,a[b+c]);}else
a.addEventListener(b,c,false);};function removeEvent(a,b,c){if(a.detachEvent){a.detachEvent('on'+b,a[b+c]);a[b+c]=null;}else

The script was so tight that I couldn’t get it any smaller than a simple removal of spaces and renaming of the variables! Both Chris’s compressor and Dean’s packer simply made the script larger! Well done, John.

Comments are closed.

%d bloggers like this: