Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way of attaching event listener to the whole html document

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?)

like image 569
Dan Avatar asked May 17 '15 10:05

Dan


People also ask

How do you add an event listener in HTML?

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.

What is the best way to attach an event handler to an 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 ).

Can I add event listener to all elements of class?

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.


1 Answers

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.

like image 138
Guffa Avatar answered Sep 21 '22 23:09

Guffa