Event Delegation in Javascript.

Event Delegation in Javascript.

ยท

4 min read

Event Delegation is not a new trick, it has been in use in several big projects already. So let's see what do we mean by event delegation.

Event delegation is a technique of adding event listeners to a parent element instead of adding it to the descendant elements. The listener gets fired whenever the event is triggered on the descendant elements due to event bubbling up the DOM.

Event bubbling provides the foundation for event delegation. So we'll start our discussion with event bubbling.

Event Bubbling

By default, almost all the events bubble up the DOM. Let's see this in action.

   <div onclick="alert('Event bubbling in action!')">
          <em>Try clicking me</em.
   </div>

In the above example, the event bubbles up to the parent div where it runs the handler.

When an event is triggered on an element, it first runs the handlers on it, then it bubbles up and runs on parent and then up to the DOM.

There's another phase Event capturing but is rarely used in real code. In event capturing, the event goes down to the element.

Event delegation in action.

Event bubbling allows us to implement one of the most powerful events handling patterns event delegation.

With event delegation, we can attach a listener to the parent element and it gets executed whenever the event occurs on any of its child nodes.

So what's the benefit?

Consider the below code,

     <ul onclick="alert('event delegation in action')">
           <li>Item 1</li>
           <li>Item 2</li>
           <li>Item 3</li>
     </ul>

The problem occurs when we need to add list items dynamically. In that case, if we do not follow the event delegation pattern and we want to listen to every child node then we must add event listeners to each node and the dynamically created node, and bind them accordingly. With event delegation, we don't need to do anything. The number of bindings can be drastically decreased by simply adding the listener to the parent element.

Another benefit is that memory footprint goes down because only one single handler is needed on the parent element, rather than having to attach event handlers on each descendant

Wrap Up

I hope you liked the content, there's more on the way. Stay Tuned! ๐Ÿ”ฅ If you have any suggestions or questions or found this article helpful, please let me know in the comments.

ย