Skip to main content Skip to secondary navigation Accessibility Feedback

.document vs .window in JavaScript

One of the students in my Vanilla JS Guidebook 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.

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