Difference between document.addEventListener and window.addEventListener?
document.addEventListener(“deviceready”, onDeviceReady, false);
document.addEventListener(“touchmove”, preventBehavior, false);
window.addEventListener(‘shake’, shakeEventDidOccur, false);
What is the difference and which is better to use?
window are different objects and they have some different events. Using
addEventListener() on them listens to events destined for a different object. You should use the one that actually has the event you are interested in.
For example, there is a
"resize" event on the
window object that is not on the
For example, the
"DOMContentLoaded" event is only on the
So basically, you need to know which object receives the event you are interested in and use
.addEventListener() on that particular object.
Here’s an interesting chart that shows which types of objects create which types of events: https://developer.mozilla.org/en-US/docs/DOM/DOM_event_reference
If you are listening to a propagated event (such as the click event), then you can listen for that event on either the document object or the window object. The only main difference for propagated events is in timing. The event will hit the
document object before the
window object since it occurs first in the hierarchy, but that difference is usually immaterial so you can pick either. I find it generally better to pick the closest object to the source of the event that meets your needs when handling propagated events. That would suggest that you pick
window when either will work. But, I’d often move even closer to the source and use
document.body or even some closer common parent in the document (if possible).
document both fit the bill (with just a few differences).
From mozilla dev network:
addEventListener() registers a single event listener on a single
target. The event target may be a single element in a document, the
document itself, a window, or an XMLHttpRequest.
So as long as you can count on your “target” always being there, the only difference is what events you’re listening for, so just use your favorite.