Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event delegation and window versus window.document

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.

like image 457
sawa Avatar asked Sep 29 '22 19:09

sawa


1 Answers

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.

like image 130
Ke Vin Avatar answered Oct 03 '22 00:10

Ke Vin