.document vs .window in JavaScript
IMPORTANT: This article is incorrect. Click here to read an updated and corrected version.
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.