1. Computing

Cross Browser Add and Remove Event Listeners

This code owes a lot to John Resig for his winning entry in the addEvent() recoding contest as well as to some of the suggested ajustments that were made on the page where the winner was announced. The main change I have made to the code as my contribution is to move the test for which version the given browser supports outside of the function so that it only needs to test once for the whole page and not once for every event being added or removed.

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

Here's an example of the way you would write your call to actually use it.

var lnk = document.getElementById('ex');
addEvent(lnk, 'click', function(event) {
  alert(this.nodeName);
  alert(event);
});

Of course just presenting the code isn't enough without a live example to show you how it works with it attached to the link in this paragraph.

©2013 About.com. All rights reserved.