Event bubbling and event capturing

what is event bubbling and event capturing in HTML?

1 Like

@manaskumarpanigrahi6
Event capturing is the process of starting the event from the root element of the document hierarchy and then propagating it down to the target element. This means that the outermost ancestor element is the first to receive the event, followed by its child elements, and so on until the target element is reached.

Event bubbling, on the other hand, is the opposite process. It starts from the target element and propagates the event up the document hierarchy to its parent elements. This means that the target element is the first to receive the event, followed by its parent elements, and so on until the outermost ancestor element is reached.

3 Likes

In JavaScript, there are two ways that events can be handled when they occur on an element: event bubbling and event capturing.

Event capturing and event bubbling are two phases of event propagation in the Document Object Model (DOM). When an event is triggered on an element, the event will first go through the capturing phase, then the target phase, and finally the bubbling phase.

Here’s a diagram that shows how event capturing and event bubbling work:

In the capturing phase, the event is triggered on the outermost parent element and works its way down to the target element. In the bubbling phase, the event is triggered on the target element and works its way up to the outermost parent element.

Here’s an example of how to use event capturing and event bubbling in JavaScript:

Click me!

const parent = document.getElementById(‘parent’);
const child = document.getElementById(‘child’);
const button = document.getElementById(‘button’);

parent.addEventListener(‘click’, function() {
console.log(‘Parent clicked!’); // event capturing
}, true);

child.addEventListener(‘click’, function() {
console.log(‘Child clicked!’); // event target
});

button.addEventListener(‘click’, function() {
console.log(‘Button clicked!’); // event bubbling
});

In this example, we have three elements: a parent div, a child div inside the parent, and a button inside the child. We attach event listeners to each element to log a message when it’s clicked.

The parent element has an event listener that uses event capturing (the third argument is true). When you click the button, the message “Parent clicked!” is logged first, followed by “Child clicked!” and “Button clicked!” in the bubbling phase. :sweat_smile: :sweat_smile:

1 Like