What is event delegation and why is it useful? Can you show an example of how to use it?

Photo by Carlos Muza on Unsplash

What is event delegation and why is it useful? Can you show an example of how to use it?

Event delegation is a technique of delegating events to a single common ancestor. Due to event bubbling, events "bubble" up the DOM tree by executing any handlers progressively on each ancestor element up to the root that may be listening to it.

or

Event delegation is a technique in JavaScript where you attach a single event handler to a parent element, instead of attaching multiple event handlers to its child elements. The idea is to take advantage of event bubbling, which means that an event triggered on a child element will also be triggered on its parent elements.

Event delegation is useful because it can greatly improve the performance of your code, especially when dealing with dynamic content, where elements are added or removed from the DOM frequently. When you use event delegation, you only need to attach one event handler to the parent element, instead of attaching multiple event handlers to each child element. This reduces the number of event handlers in memory and reduces the amount of processing required to handle events

DOM events provide useful information about the element that initiated the event via Event.target. This allows the parent element to handle behavior as though the target element was listening to the event, rather than all children of the parent or the parent itself.

This provides two main benefits:

  • It increases performance and reduces memory consumption by only needing to register a single event listener to handle potentially thousands of elements.

  • If elements are dynamically added to the parent, there is no need to register new event listeners for the.

document.querySelectorAll("button").forEach(button => {
  button.addEventListener("click", handleButtonClick)
})
document.addEventListener("click", e => {
  if (e.target.closest("button")) {
    handleButtonClick()
  }
})
                         (OR)
//htmil page conatin the li tags
document.getElementById("list").addEventListener("click", function(event) {
  if (event.target.tagName === "LI") {
    console.log("You clicked on", event.target.innerHTML);
  }
});

Did you find this article valuable?

Support Preeti Samuel by becoming a sponsor. Any amount is appreciated!