What is event bubbling in JavaScript?
In JavaScript, event bubbling is a mechanism that describes the way events propagate up through the DOM hierarchy. When an event is triggered on an element, it first triggers on that element and then "bubbles up" through all its ancestor elements.
For example, if you click on a button that is contained within a div, the click event will first trigger on the button and then propagate up to the div:
Click meIn this example, if you click on the "Click me" button, the console will log "button clicked" and then "div clicked", because the button click event is triggered first and then bubbles up to the div.
Event bubbling can be useful for delegating event handling to ancestor elements, rather than attaching event listeners to every individual element. For example, you can attach a single event listener to a parent element and then check the event.target property to determine which child element triggered the event:
- Item 1
- Item 2
- Item 3
In this example, the event listener is attached to the ul element and logs the text content of the clicked li element, even though the event bubbles up from the li to the ul element.