In this tutorial, we will learn what is event delegation model in javascrpt:

Event Delegation Model:

  • JavaScript event delegation is a technique that allows you to handle events for multiple elements with a single event handler.
  • Instead of adding an event handler to each individual element, you add it to a higher-level element, and then determine the target element that actually received the event based on the event object.

Example:

<ul id="list">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>

In this example, we want to handle the click event for each li element in the list. Instead of adding an event handler to each li element, we add it to the parent ul element:

document.getElementById("list").addEventListener("click", function(event) {
  if (event.target.tagName === "LI") {
    console.log("List item clicked:", event.target.textContent);
  }
});

When a user clicks on one of the li elements, the event handler will be triggered, and we can determine the target element that received the event based on the event.target property.

This approach is particularly useful when you have a large number of elements that you want to handle events for, as it avoids the overhead of adding an event handler to each individual element. Additionally, it allows you to dynamically add or remove elements from the list without having to worry about updating the event handlers.

Thanks for Reading…