In JavaScript, when an event is fired on an element that is nested within other elements, the event is first captured down to the right target element, and then bubbled up again. This is called Event Bubbling and Capturing.
Event Bubbling is the propagation of the same event from the innermost target element to the outermost parent element.
document.querySelector("#parent").addEventListener('click', () => {
alert('Parent Clicked!');
});
document.querySelector("#child").addEventListener('click', (event) => {
alert('Child Clicked!');
event.stopPropagation();
});
In this case, clicking on the child will first trigger the alert for the child, and then the alert for the parent due to event bubbling.
Event Capturing is the process where the event starts from the outermost parent and goes down to the target child.
document.querySelector("#parent").addEventListener('click', () => {
alert('Parent Clicked!');
}, true); // set useCapture to true
document.querySelector("#child").addEventListener('click', (event) => {
alert('Child Clicked!');
event.stopPropagation();
});
In this case, clicking on the child will first trigger the alert for the parent, and then the alert for the child due to event capturing.
We can prevent event bubbling or capturing by using event.stopPropagation(). This will stop the event from further propagation in the capturing/bubbling phase.