By the end of this lesson, you will understand event bubbling and event delegation in JavaScript.
Event bubbling is a process that occurs when an event happens on a child element and bubbles up to its parent elements. For example, imagine a button inside a div. When you click the button, the click event first triggers the button and then the parent div, if it has an event listener attached.
File: bubbling.js
const button = document.querySelector('#myButton');
const div = document.querySelector('#myDiv');
button.addEventListener('click', () => {
alert('Button Clicked!');
});
div.addEventListener('click', () => {
alert('Div Clicked!');
});
This script sets up listeners for both a button and a div. When you click the button, it alerts you that the button was clicked, and then it alerts again that the div was clicked.
Event delegation uses event bubbling to manage events on multiple elements. Instead of adding an event listener to each element, you place one listener on a parent element. This improves performance, especially with many child elements.
Create a simple HTML structure with multiple buttons inside a div. Use event delegation to handle button clicks. When a button is clicked, display which button was clicked using the alert function.
File: delegation.js
const buttonContainer = document.querySelector('#buttonContainer');
buttonContainer.addEventListener('click', (event) => {
if (event.target.tagName === 'BUTTON') {
alert(`Button ${event.target.textContent} clicked!`);
}
});
event.stopPropagation().