Delegation event and window against window. Document

I want to do event delegation and capture all events occurring on the DOM object with an event handler associated with the entire document. Is there a difference between binding events to a 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.

+5
source share
1 answer

There is a difference between window and window.document . window refers to the part of the browser being viewed and is always loaded first. window.document is the body of your page, where all content and the DOM are displayed and includes, for example, all parts that are hidden until their scrolling shows them.

The events you specified are user-initiated events and will always affect the visible port of the window. I canโ€™t think of any situation when you will receive, for example. Click event outside the viewport. As far as I know, you canโ€™t even generate an event similar to one that is not tied to a specific element, but to a position on the screen. The same applies to keyup , keydown , .... events.

To answer your question, there is no functional difference between binding your events to window or window.document . The only difference is the this property inside function calls. For me, it is more advisable to associate the event with window.document with the DOM rather than with window .

+4
source

Source: https://habr.com/ru/post/1203376/


All Articles