This website collects cookies to deliver better user experience
Event Delegation in JS
Event Delegation in JS
Event delegation is a concept to handle events in JS in more performant way. It uses the concept of event bubbling to achieve the same. Event capturing concept can also be used but event bubbling is the preferred approach.
Suppose there is list of items, i.e. lis inside an uland clicking on each li some action is expected to occur. So the common approach is to add event listener to each li in the list.
const items =document.querySelectorAll('#list li');consthandleClick=()=>{// do something here ...};// listener added to each liitems.forEach(item=>{ item.addEventListener('click', handleClick)});
In this approach the number of event handlers attached are same as the number of lis present in the list, which will consume more JS memory.
So to solve this issue we can use the Event delegation approach here.
With event delegation
const list =document.querySelector('#list');consthandleClick=(event)=>{if(event.target.tagName==='LI'){// do something here}};// listener added to ullist.addEventListener('click', handleClick);
In the above sample code, only one event handler is being added to the parent ul#list. Now in the handler if the target.tagName is a LI then the required task is performed. Thus the number of handlers are reduced to one, which consumes less JS memory.