Reputation: 1
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>
Upvotes: 0
Views: 73
Reputation: 510
There are 2 concepts you need to know in order to understand why this happens:
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
Upvotes: 1