Let's consider the problem of capturing mousemove
on the whole HTML document.
I know four objects to which event listener can be attached:
window
, document
, document.body
, document.documentElement
After simple tests it seemed to me that attaching to any of them has the same effect.
$(window).on('mousemove', function(){console.log(1)})
I was wondering if there is any difference I don't know about (performance, compatibility?)
The addEventListener() method allows you to add event listeners on any HTML DOM object such as HTML elements, the HTML document, the window object, or other objects that support events, like the xmlHttpRequest object.
The most flexible way to set an event handler on an element is to use the EventTarget. addEventListener method. This approach allows multiple listeners to be assigned to an element, and for listeners to be removed if needed (using EventTarget. removeEventListener ).
To add an event listener to all elements with class: Use the document. querySelectorAll() method to select the elements by class. Use the forEach() method to iterate over the collection of elements.
There are two potential issuses with binding the event to the document.body
object:
Some browsers doesn't allow accessing the body object before the content in the page has begun being parsed, so binding the event directly in the head won't work. You need to bind it from the load
or ready
event, or from code inside the body.
In standards compliant mode (HTML 4, XHTML, HTML5) the body element doesn't automatically cover the entire window. It will only be as large as it needs to contain the content, and if it has a margin that is not covered by the body element.
Also, if the page contains frames, then this won't work. In that case, follow steps explained here.
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