简体   繁体   中英

addEventListener - attaching to document versus document.body

I am writing a drag drop handler and wish to set the eventListeners to the highest level - which I presumed would be the body . However, I noticed in the example at MDN , they set the listeners to document versus document.body which leads me to ask why would this be preferable and in general, why would I choose listeners attached to one versus the other (and do they both support the same listeners)?

So when do I use document.body.addeventListener() versus document.addEventListener() ?

UPDATE This SO question addresses WHEN to bind the events to document versus at the element level. Very helpful.

UPDATE2 Interestingly enough, when document.addEventListener() is set for all the drag drop listeners, Firefox hangs with a drag (Chrome does not). When I change it to document.body.addEventListener() for dragEnter, dragOver, dragLeave, drop it all works fine. Seems like dragStart wants to be on the document however.

body is but one element within a document . document is more "top-level" than body . But, in the HTML, there is no tag the explicitly denotes the document itself, thus in HTML, body gets used as the next best thing. Since events bubble, when the body reports loaded, it is generally safe to say that the document is loaded as well. You can see a list of events and what objects they work with/on here .

That issue aside, inline event handlers should be avoided in favor of setting up event handlers in JavaScript using addEventListener because inline event handlers:

  1. Create spaghetti-code that is harder to read, leads to duplicated code and doesn't scale well.

  2. Implicitly create global wrapper functions that alter the this binding within the supplied event handling code. This can cause your handler to not work properly.

  3. Don't follow the W3C DOM Event Handling standard and are not as robust as addEventListener .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM