Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

window.document.addEventListener vs window.addEventListener

Tags:

javascript

dom

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) {...});?

like image 377
isaac9A Avatar asked Oct 20 '22 00:10

isaac9A


1 Answers

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.

like image 108
Quentin Avatar answered Oct 21 '22 21:10

Quentin