Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 655
auroranil Avatar asked Jan 27 '12 03:01

auroranil


People also ask

Why do we use addEventListener?

The addEventListener() method makes it easier to control how the event reacts to bubbling. When using the addEventListener() method, the JavaScript is separated from the HTML markup, for better readability and allows you to add event listeners even when you do not control the HTML markup.

What's the difference between event handlers & addEventListener in JS?

There's no difference; it's just different terminology for the same thing. There are different ways of associating functions with DOM elements for the purpose of event handling, that's all.

What is the benefit of using addEventListener instead of inline event handlers?

addEventListener() has multiple advantages: Allows you to register unlimited events handlers and remove them with element. removeEventListener() . Has useCapture parameter, which indicates whether you'd like to handle event in its capturing or bubbling phase.

What is difference between window addEventListener and document addEventListener?

Basically, there is no difference between using a document and a window. You can use any of those as per your preference. Some functions like a scroll and resize should be available in the window. addEventListener.


1 Answers

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()).

like image 114
alex Avatar answered Oct 15 '22 10:10

alex