Event Propogaation Bubling & caputring :
JavaScript event :
Events, in JavaScript, are occurrences that can trigger certain functionality,
and can result in certain behaviour.
A common example of an event, is a “click”, or a “hover”.
You can set listeners to watch for these events that will trigger your desired functionality.
propagation :
Propagation refers to how events travel through the Document Object Model (DOM) tree.
The DOM tree is the structure which contains parent/child/sibling elements in relation to
each other.
You can think of propagation as electricity running through a wire, until it
reaches its destination.
The event needs to pass through every
node on the DOM until it reaches the end, or if it is forcibly stopped.
Event Bubbling and Capturing
Bubbling and Capturing are the two phases of propagation.
In their simplest definitions,
bubbling travels from the target to the root, and capturing travels from the root to the target.
propagation :
Event.stopPropagation()
These two methods are used for solving the previously mentioned problem regarding event propagation. Calling Event.stopPropagation() will prevent further propagation through the DOM tree,
and only run the event handler from which it was called.
function first() {
console.log(1);
}
function second() {
console.log(2);
}
var button = document.getElementById("button");
var container = document.getElementById("container");
button.addEventListener("click", first);
container.addEventListener("click", second);
In this example, clicking the button will cause the console to print 1, 2.
If we wanted to modify this so that only the button’s click event is triggered, we could use Event.stopPropagation()
to immediately stop the event from bubbling to its parent.
function first(event) {
event.stopPropagation();
console.log(1);
}
This modification will allow the console to print 1, but it will end the event chain right away, preventing it from reaching 2.