Difference between document.addEventListener and window.addEventListener?

Viewed 154215

While using PhoneGap, it has some default JavaScript code that uses document.addEventListener, but I have my own code which uses window.addEventListener:

function onBodyLoad(){
  document.addEventListener("deviceready", onDeviceReady, false);
  document.addEventListener("touchmove", preventBehavior, false);
  
  window.addEventListener('shake', shakeEventDidOccur, false);
}

What is the difference and which is better to use?

4 Answers

The window binding refers to a built-in object provided by the browser. It represents the browser window that contains the document. Calling its addEventListener method registers the second argument (callback function) to be called whenever the event described by its first argument occurs.

<p>Some paragraph.</p>
<script>
  window.addEventListener("click", () => {
    console.log("Test");
  });
</script>

Following points should be noted before select window or document to addEventListners

  1. Most of the events are same for window or document but some events like resize, and other events related to loading, unloading, and opening/closing should all be set on the window.
  2. Since window has the document it is good practice to use document to handle (if it can handle) since event will hit document first.
  3. Internet Explorer doesn't respond to many events registered on the window,so you will need to use document for registering event.

In my opinion, it is generally better to pick the closest object to the source of the event that meets your needs when handling propagated events.

So, if you want the event to happen to the element, it's better to use window.addEventListener() (assume the window variable is an element) because the most important thing here when listening to an event is that the code and event execution work faster: the only thing that matters in this case.

Related