Enjoy 20% off all plans by following us on social media. Check out other promotions!
Quiz Questions

Describe event bubbling

Topics
JAVASCRIPTHTML
Edit on GitHub

Event bubbling is a propagation mechanism in the DOM (Document Object Model) where an event, such as a click or a keyboard event, is first triggered on the target element that initiated the event and then propagates upward (bubbles) through the DOM tree to the root of the document.

Bubbling phase

During the bubbling phase, the event starts at the target element and bubbles up through its ancestors in the DOM hierarchy. This means that the event handlers attached to the target element and its ancestors can all potentially receive and respond to the event.

Here's an example using modern ES6 syntax to demonstrate event bubbling:

// HTML:
// <div id="parent">
// <button id="child">Click me!</button>
// </div>
const parent = document.getElementById('parent');
const child = document.getElementById('child');
parent.addEventListener('click', () => {
console.log('Parent element clicked');
});
child.addEventListener('click', () => {
console.log('Child element clicked');
});

When you click the "Click me!" button, both the child and parent event handlers will be triggered due to event bubbling.

Stopping propagation

Event propagation can be stopped during the bubbling phase using the stopPropagation() method. If an event handler calls stopPropagation(), it prevents the event from further bubbling up the DOM tree, ensuring that only the handlers of the elements up to that point in the hierarchy are executed.

Event delegation

Event bubbling is the basis for a technique called "event delegation", where you attach a single event handler to a common ancestor of multiple elements and use event delegation to handle events for those elements efficiently. This is particularly useful when you have a large number of similar elements, like a list of items, and you want to avoid attaching individual event handlers to each item.

References

Edit on GitHub