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. li
s inside an ul
and 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.
HTML
<ul id='list'>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
...
</ul>
Without event delegation
const items = document.querySelectorAll('#list li');
const handleClick = () => {
// do something here ...
};
// listener added to each li
items.forEach(item => {
item.addEventListener('click', handleClick)
});
In this approach the number of event handlers attached are same as the number of li
s 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');
const handleClick = (event) => {
if (event.target.tagName === 'LI') {
// do something here
}
};
// listener added to ul
list.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.
For more info about event bubbling
Top comments (0)