1

When I run this code, why does the .body event fire first?

document.addEventListener('click', function() {
  console.log('The document was clicked');
});

document.body.addEventListener('click', function() {
  console.log('The document body was clicked');
});
j08691
  • 204,283
  • 31
  • 260
  • 272
Sam
  • 11
  • 2

2 Answers2

5

It doesn't run faster, it runs sooner.

The event bubbles up from the element you clicked until it reaches the body (where the event listener on the body is fired) and then it continues bubbling up until it reaches the document (where the event listener there is fired).

See MDN for more detail, diagrams, and how to capture events in the capturing phase.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Thank you I have gone through the bubbling but it seems I didn't catch it very well. but I get it now – Sam Jul 12 '19 at 11:51
0

simply because both of them will be activated by the bubble phase so it runs from downside to upside so the body.listener will work first then the document.listener