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.


🔥 Hot off the press! I just launched a new pocket guide. Learn how to build interactive web apps with vanilla JavaScript.

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