Why does the document.addEventListener event run after document.body.addEventListener? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Why does the document.addEventListener event run after document.body.addEventListener? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

why does the .body event fire first and the document event fire next, explain with details?

<!DOCTYPE html>
<html>
<head> </head>
<body>
  <img src="https://www.wallpapertip.com/wmimgs/83-838381_html-wallpaper-background-code-coding-tags.jpg"
    width="100%" />
  <script>
    document.addEventListener('click', function () {
      console.log('The document was clicked');
    });

    document.body.addEventListener('click', function () {
      console.log('The document body was clicked');
    });
  </script>
</body>
</html>

Answer

There are 2 concepts you need to know in order to understand why this happens:

  • Bubbling
  • Capturing

Bubbling is the default behaviour when adding event listeners. With bubbling, when an event happens on an element, it runs any handlers on that element first, and then bubbles up the DOM tree to it’s parents.

Capturing happens in the opposite direction. The parents handler is first invoked before travelling to its children.

The document is the highest level parent in the DOM tree; therefore, body is a child of the document

If you wish to swap the default behaviour of bubbling, and want the parent elements handler to fire prior to it’s children, the addEventListener method takes an optional third parameter:

addEventListener(event, function, true)  // <--- true states to enable capturing
We are here to answer your question about Why does the document.addEventListener event run after document.body.addEventListener? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji