Event Delegation

Posted on by By Nikhilesh, in Front End, Javascript | 0

First let’s create HTML of an unordered list (ul).
HTML

<ul id="todo-app">
	<li class="item">Item 1</li>
        <li class="item">Item 2</li>
        <li class="item">Item 3</li>
        <li class="item">Item 4</li>
</ul>

 

Event Delegation technique:

Suppose if you have attached the event listener click on li rather than on ul, then you are attaching the listener to every li element and if there are n number of li elements, this is not the efficient way to attach the event listeners. Rather attach the event listener to ul and call or target only specific li element as listener. This is called event delegation.

Wrong implementation:

document.addEventListener('DOMContentLoaded', function() {
  
  let app = document.getElementById('todo-app');
  let items = app.getElementsByClassName('item');
  
  // attach event listener to each item
  for (let item of items) {
    item.addEventListener('click', function() {
      console.log('Wrong: You clicked on item: ' + item.innerHTML);
    });
  }
  
});

 

Correct implementation:

document.addEventListener("DOMContentLoaded", function() {
  let app = document.getElementById("todo-app");
  
  app.addEventListener("click", function(e) {
    if(e.target && e.target.nodeName === "LI") {
      let item = e.target;
      console.log("Correct: You clicked on: " + item.innerHTML);
    }
  });
});
logo

Best Open Source Business Intelligence Software Helical Insight is Here

logo

A Business Intelligence Framework

-By
Uma Maheswar
Helical IT Solution

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments