addEventListener vs onclick

What's the difference between addEventListener and onclick ?

var h = document.getElementById("a");
h.onclick = dothing1;
h.addEventListener("click", dothing2);

The code above resides together in a separate .js file, and they both work perfectly.


Both are correct, but none of them are "best" per se, and there may be a reason the developer chose to use both approaches.

Event Listeners (addEventListener and IE's attachEvent)

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

element.attachEvent('onclick', function() { /* do stuff here*/ });

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

element.addEventListener('click', function() { /* do stuff here*/ }, 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]:

var myFunctionReference = function() { /* do stuff here*/ }

element.attachEvent('onclick', myFunctionReference);
element.addEventListener('click', myFunctionReference , false);

Another important feature of addEventListener is the final parameter, which controls how the listener reacts to bubbling events[doc]. I've been passing false in the examples, which is standard for probably 95% of use cases. 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:

<a id="testing" href="#" onclick="alert('did stuff inline');">Click me</a>

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:

element.onclick = function () { /*do stuff here */ };

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

var element = document.getElementById('testing');
element.onclick = function () { alert('did stuff #1'); };
element.onclick = function () { alert('did stuff #2'); };

... when you clicked the element, you'd only see "Did stuff #2" - you overwrote the first assigned of the onclick property with the second value, and you overwrote the original inline HTML onclick property too. Check it out here: http://jsfiddle.net/jpgah/.

Which is Best?

The question is a matter of browser compatibility and necessity. Do you currently need to attach more than one event to an element? Will you in the future? Odds are, you will. attachEvent and addEventListener are necessary. If not, an inline event will do the trick.

jQuery and other javascript frameworks encapsulate the different browser implementations of DOM level 2 events in generic models so you can write cross-browser compliant code without having to worry about IE's history as a rebel. Same code with jQuery, all cross-browser and ready to rock:

$(element).on('click', function () { /* do stuff */ });

Don't run out and get a framework just for this one thing, though. You can easily roll your own little utility to take care of the older browsers:

function addEvent(element, evnt, funct){
  if (element.attachEvent)
   return element.attachEvent('on'+evnt, funct);
  else
   return element.addEventListener(evnt, funct, false);
}

// example
addEvent(
    document.getElementById('myElement'),
    'click',
    function () { alert('hi!'); }
);

Try it: http://jsfiddle.net/bmArj/

Taking all of that into consideration, unless the script you're looking at took the browser differences into account some other way (in code not shown in your question), the part using addEventListener would not work in IE versions less than 9.

Documentation and Related Reading

  • W3 HTML specification, element Event Handler Attributes
  • element.addEventListener on MDN
  • element.attachEvent on MSDN
  • Jquery.on
  • quirksmode blog "Introduction to Events"
  • CDN-hosted javascript libraries at Google

  • The difference you could see if you had another couple of functions:

    var h = document.getElementById('a');
    h.onclick = donothing1;
    h.onclick = donothing2;
    
    h.addEventListener('click', donothing3);
    h.addEventListener('click', donothing4);
    

    Functions 2, 3 and 4 work, but 1 does not. This is because addEventListener does not overwrite existing event handlers, whereas onclick overrides any existing onclick = fn event handlers.

    The other significant difference, of course, is that onclick will always work, whereas addEventListener does not work in Internet Explorer before version 9. You can use the analogous attachEvent (which has slightly different syntax) in IE <9.


    In this answer I will describe the three methods of defining DOM event handlers.

    element.addEventListener()

    Code example:

    const element = document.querySelector('a');
    element.addEventListener('click', event => event.preventDefault(), true);
    <a href="//google.com">Try clicking this link.</a>
    链接地址: http://www.djcxy.com/p/51950.html

    上一篇: addEventListener触发两次

    下一篇: addEventListener vs onclick