Event Listeners (addEventListener and IE’s attachEvent)

Earlier versions of IE implement javascript differently from pretty much every other browser. With versions less than 9, you use the attachEvent [doc] method, like this:

1

2

3

element.attachEvent('onclick',function(){

console.log("codingrepo.com");

});

In most other browsers (including IE 9 and above), you use addEventListener [doc], like this:

1

2

element.addEventListener('click',function(){

console.log("codingrepo.com");},false);

Using this approach (DOM Level 2 events), you can attach a theoretically unlimited number of events to any single element. The only practical limitation is client-side memory and other performance concerns, which are different for each browser.

The examples above represent using an anonymous function[doc]. You can also add an event listener using a function reference [doc] or a closure [doc]:

1

2

3

4

5

6

7

8

9

varcodingrepoFunction=function(){

console.log("codingrepo.com");

}

element.attachEvent('onclick',codingrepoFunction);

element.addEventListener('click',codingrepoFunction,false);

//output

codingrepo.com

Another important feature of addEventListener is the final parameter, which controls how the listener reacts to bubbling events [doc]. In the examples, it has been passed false which is default setting. There is no equivalent argument for attachEvent, or when using inline events.

Inline events (HTML onclick=”” property and element.onclick)

In all browsers that support javascript, you can put an event listener inline, meaning right in the HTML code. You’ve probably seen this:

Most experienced developers shun this method, but it does get the job done; it is simple and direct. You may not use closures or anonymous functions here (though the handler itself is an anonymous function of sorts), and your control of scope is limited.

The other method you mention:

1

2

3

element.onclick=function(){

console.log("codingrepo.com");

};

… is the equivalent of inline javascript except that you have more control of the scope (since you’re writing a script rather than HTML) and can use anonymous functions, function references, and/or closures.

The significant drawback with inline events is that unlike event listeners described above, you may only have one inline event assigned. Inline events are stored as an attribute/property of the element [doc], meaning that it can be overwritten.

Using the example <a> from the HTML above:

1

2

3

4

5

6

varelement=document.getElementById('codingrepo');

element.onclick=function(){console.log("codingrepo.com #1")};

element.onclick=function(){console.log("codingrepo.com #2")};

//output

codingrepo.com#2

Only “codingrepo.com #2” will be seen after clicked the link because the first assigned of onclick property with the value “codingrepo.com #1” is overwritten by second assigned with the value “codingrepo.com #2”.

You can also roll your own little utility to fit the older browsers as below: