1. Computing & Technology

Modular JavaScript Library

Cross Browser Event Library

The most flexible way of adding event processing to your web page is using event listeners. Instead of completely overwritiing any existing event processing attached to the element the way event handlers do, an event listener adds to the existing processing and so the event processing required by different scripts that you add to the page can be processed independently without needing any knowledge of the other script.

The problem is that Internet Explorer doesn't support event listeners but instead has its own equivalent functionality. One way to overcome this is to use an existing JavaScript library that takes care of this for you. Including a large library just to use one small piece of it isn't very efficient though.

The script offered here is a much smaller alternative for those who want to simplify the way that they add and remove event processing. This script creates a JavaScript object called $E which contains methods for adding and removing events that will work in all common browsers including Internet Explorer.

As an example of how to use this object, here's how you can add the function myclick() to be run when a click event is triggered on an element in the page having an id of ex.

var lnk = document.getElementById('ex');
// var lnk = new $O('ex'); /* alternative to above if using $O */
$E.add(lnk, 'click', myclick);

Here's a list of all the properties and methods that the $E object provides for you:

Properties

This object currently has no properties.

Methods

  • add(o,t,f) - adds event processing
  • remove(o,t,f) - removes event processing

The first parameter passed to the add and remove methods can be either a DOM element (such as you would access using document.getElementById) or a $O object. The second parameter is the type of event that you are adding or removing from the element referenced in the first parameter (for example if you want to add processing to handle a mousedown event then you'd pass in the value 'mousedown' in this parameter - note that event listeners unlike event handlers do not start with 'on'). The third parameter is the function that is to be added to be run when the event is triggered or which is to be removed. To remove a function the exact same value needs to be passed as was used when it was added so that the appropriate processing can be updated.

To get a copy of this object to use in your scripts simply copy the following JavaScript and insert it in your page were needed. The above properties and methods will then be available for you to use in your code.

©2012 About.com. All rights reserved.

A part of The New York Times Company.