Event delegation is a technique in JavaScript where a single event listener is added to a parent element instead of adding multiple event listeners to individual child elements. This is particularly useful for managing events on dynamically generated elements or when there are many child elements.
Here’s how it works:
- Event Bubbling: When an event is triggered on an element, it first runs the handlers on that element and then bubbles up to the parent elements, running their handlers as well.
- Using a Single Event Listener: By placing an event listener on a common ancestor of all the elements that need to be monitored, you can capture events as they bubble up.
- Identifying the Target: Within the event handler, you can determine the actual target of the event using the
event.target
property and perform the necessary action.
Example:
// Parent element const parent = document.getElementById('parent'); // Event delegation parent.addEventListener('click', function(event) { if (event.target && event.target.matches('button.someClass')) { console.log('Button clicked:', event.target); } });
Event delegation is efficient and helps in reducing memory usage and improving performance, especially when dealing with large lists or dynamic content.