Picture

Hi, I'm Boopathi Rajaa.

Hacker, Dancer, Biker, Adventurist

Usage of addEventListener in JavaScript

As a continuation of the topic discussed in the previous post, addEventListener is a function that is available as a member function to all elements of type “Object" in JavaScript. The usage of addEventListener would be as follows:

var myElement = document.getElementById("myId");
myElement.addEventListener("<event>",
    handlerFunction,
    /*useCapture:Boolean = */ true);

Now I’m not going to discuss much about this member function in detail. What rather needed is that the advantage of using this type of assigning handlers to a function.

When using this function, you always add an extra definition to the handler. In other words, you can attach more than one handlers to an Object. Also it works on any DOM element, not only just HTML elements.

One can use the third parameter to set the use of Capturing of Bubbling of events.

Well, as it is said, Microsoft always does stuff in its own way, IE has conflicts with this function. There is no method for a DOM element in IE, named addEventListener. Instead it has an attachEvent() function, that will do the exact job. The differences between these two events are

  1. attachEvent doesn’t provide the option to trigger the usage of Capturing or Bubbling. You have to separately use a setCapture method.

  2. As said attachEvent works only in IE.

To avoid this situation it is good to define a function that will handle both the situations. Just adding an extra definition to the Object data type in javascript will be enough. This method will handle the browser variations. This is a sample function that I wrote.

    Object.prototype.addEvent = function(evt, handler, useCapt) {
    //JUST A CHECK TO HANDLE “onclick" and “click" as evt
    if(evt.match("^on")) evt = evt.substr(2);
    if(this.attachEvent) return this.attachEvent(evt, handler); // FOR IE
    else if(this.addEventListener) return this.addEventListener('on'+evt, handler, useCapt); // OTHERS
    else { //IF BOTH FAILS
        this['on'+evt] = handler;
        return this;
      }
    }

This can be used as myElement.addEvent("onclick", handler, false);

If I’m wrong somewhere in this context, just quote the mistakes in comment. Would correct it. Thank you for your review.