Search code examples
javascriptdom-events

What is the difference of using addEventListener?


What is the main difference between of using this:

document.addEventListener('mousedown', function() {
    // code
}, false);

...and this?

document.onmousedown = function() {
    // code
}

Will there be any different result or any cause?

Solution

  • onclick is a property, like the onclick attribute can be placed in HTML. It has best browser support, however, it is primitive, as reassigning it overwrites the first (like any object property).

    addEventListener(), as the name suggests, allows you to register multiple callbacks for an element and event type. This allows you to have multiple mousedown events for the same element. Before IE9, IE had their own attachEvent() which is similar (you must specify the on part too with attachEvent()).