Reputation: 11
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');
});
Upvotes: 1
Views: 1311
Reputation: 27
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
Upvotes: 0
Reputation: 943624
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.
Upvotes: 5