JavaScript: Difference between addEventListener and onclick

In general, there are two differences as below:

1. addEventListener does not overwrite existing event handlers on elements, whereas onclick overrides any existing onclick = function event handlers.

2. addEventListener does not works in older versions of Internet Explorer ( > IE 9 ) which uses attachEvent instead ( < IE 9 ), whereas onclick works all the browsers.

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:

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

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]:

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:

… 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:

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

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

Documentation and Related Reading

Leave a Reply

Your email address will not be published. Required fields are marked *