Event delegation is a
technique in JavaScript for handling events more efficiently by taking advantage of event bubbling. Instead of attaching event listeners to individual elements, you attach a single event listener to a parent element. When an event occurs on a child element, the event bubbles up to the parent, where the event listener is triggered. Inside the event listener, you can use the `event.target` property to determine which child element actually triggered the event and perform the appropriate action.
There are several benefits to using event delegation:
1.
Reduced memory usage: By attaching a single event listener to a parent element, you avoid the need to attach multiple listeners to each child element, which can consume more memory.
2.
Dynamic elements: Event delegation works well with elements that are added or removed dynamically, as you don't need to attach or detach event listeners when the DOM changes.
3.
Improved performance: Fewer event listeners can lead to better performance, especially in cases where there are many elements that require the same event handling.
Here's an example of event delegation in action:
```const list = document.querySelector('ul');
list.addEventListener('click', (event) => { const targetElement = event.target;
if (targetElement.tagName === 'LI') { console.log('List item clicked:', targetElement.textContent); }});```
In this example, I attach a click event listener to a `
` element. When a list item (`- `) is clicked, the event bubbles up to the `
`, triggering the event listener. Inside the listener, I check if the event.target is an `- ` element and perform the desired action.