Skip to main content Accessibility Feedback

.document vs .window in JavaScript

One of the students in my Vanilla JS Slack room asked me why I use document instead of window with addEventListener() click events. In otherwords, why this:

document.addEventListener('click', function (event) {
    // Do something..
}, false);

Instead of this:

window.addEventListener('click', function (event) {
    // Do something..
}, false);

The short answer: they do the same exact thing.

Functionally, there’s no difference. I prefer to call the DOM object lowest in the tree that satisfies our needs. window works just fine, but document does the same thing. It’s all a matter of preference.

That said, some events, like scroll and resize, must be attached to the window. But otherwise, use whichever one fits your coding style best.


🚀 Make 2018 the year you master JavaScript! My pocket guides and mini courses are short, focused, and made for beginners. You can do this!

Have any questions or comments about this post? Email me at chris@gomakethings.com or contact me on Twitter at @ChrisFerdinandi.

Get Daily Developer Tips