isaac9A
isaac9A

Reputation: 903

window.document.addEventListener vs window.addEventListener

window.document.addEventListener = function(event) {...}

window.addEventListener = function(event) {...}

What is the difference between these two lines of code? I get that window and document object are two different objects with different properties and this site provides a good visual guide to the difference. Still I don't see the difference between what these two lines of code are doing.

To further clarify: what is the difference in doing something like this: window.addEventListener('mousemove', function (event) {...}); and doing something like this window.document.addEventListener('mousemove', function (event) {...});?

Upvotes: 5

Views: 9751

Answers (1)

Quentin
Quentin

Reputation: 943108

There are addEventListener methods on most DOM objects, as well as on the window itself. Events bubble and trigger event listeners on the element on which the event starts and its ancestors.

The two pieces of code there overwrite the addEventListener on different levels.

If you were to call the original method, it would rarely (if ever) make any difference which of those objects you called it on. It would make a difference if you were to compare, for example:

window.addEventListener('click', handler);
document.querySelector('button', handler);

Since one would capture all the clicks in the document and the other would only capture those on the first button element.

Upvotes: 3

Related Questions