This is an technique well described by Mohammad Basit in a Medium blog post.
The idea is :
Instead of attaching an event listener to each individual child element, you attach a single event listener to the parent element and use it to listen for events that occur on the child elements.
Mohammad Basit
Here is Mohammad’s code
const parentElement = document.querySelector('.parent');
parentElement.addEventListener('click', function(event) {
if (event.target.classList.contains('child')) {
console.log('Clicked on child element');
}
});
The code for the above is even simpler. The if
statement wasn’t necessary because all child elements are clickable.
const buttons = document.querySelector('.buttons');
buttons.addEventListener('click', e => {
let btnNo = e.target.textContent;
alert('This is from' + btnNo);
})
Chat GPT
Finally I thought I would ask Chat GPT to weigh in on event delegation:
Event delegation in Javascript is a technique that allows an event handler to be attached to a parent element, instead of individual elements. This means that when an event is triggered on a child element, the event handler will be executed on the parent element.
The pros of using event delegation are that it allows for more efficient use of memory and resources, since only one event handler needs to be attached to the parent element. It also makes it easier to add new elements to the page, since they will automatically inherit the same event handlers as their parent.
The cons of using event delegation are that it can be difficult to debug since there is only one handler attached to the parent element. It can also make it difficult to identify which child element triggered an event, since all events are handled by the same handler.
Chat GPT