22. Advanced Event Handling & Delegation
Why Advanced Event Handling Matters
Events are at the core of interactive web pages. Handling them efficiently and correctly is crucial for performance, especially when dealing with dynamic content or large numbers of elements.
Event Listeners Basics
The standard way to listen for events is using `addEventListener`. This allows multiple handlers for the same event without overwriting existing ones.
const button = document.getElementById('myButton');
button.addEventListener('click', function(event) {
console.log('Button clicked!', event);
});Event Object & Properties
When an event triggers, it passes an event object containing useful properties and methods. Examples include `target`, `currentTarget`, `type`, and `preventDefault()`.
document.addEventListener('click', (event) => {
console.log('Clicked element:', event.target);
console.log('Event type:', event.type);
});Event Propagation: Bubbling & Capturing
Events propagate through the DOM in two phases: capturing (top-down) and bubbling (bottom-up). By default, `addEventListener` listens during the bubbling phase.
const parent = document.getElementById('parent');
const child = document.getElementById('child');
parent.addEventListener('click', () => console.log('Parent clicked!'), false); // bubbling
child.addEventListener('click', () => console.log('Child clicked!'));You can use the third parameter of `addEventListener` to `true` to listen during the capturing phase instead.
Event Delegation
Instead of adding listeners to every child element, attach a single listener to a parent. Use `event.target` to identify which child triggered the event. This improves performance and works for dynamically added elements.
const list = document.getElementById('itemList');
list.addEventListener('click', (event) => {
if(event.target && event.target.nodeName === 'LI'){
console.log('Clicked item:', event.target.textContent);
}
});This technique allows you to handle events for elements that don’t exist yet at the time the listener is attached.
Removing Event Listeners
Always remove listeners if they are no longer needed to prevent memory leaks, especially in single-page apps.
function handleClick() {
console.log('Clicked!');
button.removeEventListener('click', handleClick);
}
const button = document.getElementById('myButton');
button.addEventListener('click', handleClick);Mini Challenge
1. Create a dynamic list where users can add new items. 2. Use event delegation to listen for clicks on any list item and log its text. 3. Add a button to remove an item and demonstrate removing its event listener.