About
event propagation is a mechanism in which an event is propagated to all its ascendant (ancestore).
Event bubbles or propagates up the DOM tree: it starts with where the event happened, and then goes up the DOM tree.
Example
Navigation link
- Any time one of anchor tags is clicked,
- a click event is fired for that anchor,
- and then bubbles up the DOM tree,
- triggering each of its parent click event handlers:
Example with the click event
- The html with:
- the link to click in order to create a click event
- a div as parent to demonstrate that this element receives also the click event.
<div>
<a href="#">Bubbles demo - click me</a>
</div>
- The javascript that select the anchor, and attach a function when it's clicked.
document.querySelector('a').onclick = function(event) {
event.preventDefault();
console.log("The link was clicked");
console.log('Does the onClick event bubbles ? '+event.bubbles);
}
- To show that the click event bubble up to the parent of the link, we add a handler on the div that responds to click event
document.querySelector('div').onclick = function(event) {
console.log("The div was clicked showing that the event bubbles up");
}
Management
see
The bubbles read-only property of an Event indicates whether the event bubbles up through the DOM or not.
stop
- stopImmediatePropagation() to not call any further listeners for the same event at the same level in the DOM