Reputation: 5670
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.
Upvotes: 7
Views: 3947
Reputation: 65808
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:
Create spaghetti-code that is harder to read, leads to duplicated code and doesn't scale well.
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.
Don't follow the W3C DOM Event Handling standard and are not as robust as addEventListener
.
Upvotes: 4