I want to do event delegation and capture all events happening on a DOM object by an event handler bound to the entire document. Is there any difference between binding the events to window
as in:
window.addEventListener(event, function(e){
var obj = e.target;
... // if `obj` is a certain kind of object, then do something
}, false);
and window.document
as in the following?
window.document.addEventListener(event, function(e){
var obj = e.target;
... // if `obj` is a certain kind of object, then do something
}, false);
event
is some kind of event like 'click'
, 'mouseover'
, etc.
There is a difference between window
and window.document
. window
relates to the viewable part of the browser and is always loaded first. The window.document
is the body of your page where all the content and DOM is displayed and includes e.g. all parts that are hidden until scrolling to them reveals them.
The events you listed are user triggered events and will always affect the viewable port of the window. I can't think of any situation where you would receive e.g. a click event that is outside your view port. As far as I know you cannot even generate an event like that which is not bound to a specific element but to a position on the screen. Same goes for keyup
, keydown
, ... events.
To answer your question, there is no functional difference between binding your events to window
or window.document
. The only thing that is different is the this
property inside the function calls. To me it makes a little more sense to bind an event to window.document
the DOM rather than to the window
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With