JavaScript optimization - Event delegation

Dealing with events in JavaScript is easy when you are working with jQuery or other language. Adding .on() or addEventListener() to next object is one of the ways but when you have group of objects to which you are still adding new objects you have to repeat adding events to each new element. With Event delegation you can omit this problem.

HTML of Event Delegation:

<a id="add-button">Add</a>
<ul id="parent">
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
</ul>

JavaScript code of Event Delegation:

document.getElementById("parent").addEventListener("click",function(e) {
    if(e.target && e.target.nodeName.toLowerCase() == "li") {
    e.target.textContent = parseInt(e.target.textContent)+1;
    }
});

document.getElementById("add-button").addEventListener("click", function(e) {  
  var para = document.createElement("li");
  var node = document.createTextNode("0");
  para.appendChild(node);

  document.getElementById("parent").appendChild(para);
})

CODEPEN of Event Delegation:

See the Pen FwftB by FEDojo.com (@fedojo_com) on CodePen.

As you can see in preview each element in <ul id=”parent”> has click listener. Element <a id=”add-button”> is adding new element which has event listener added. You dont have to repeat addEventListener() to each element so when you have more events added on element (for example mouseenter, mouseleave etc) they are added automaticaly.

How to Event Delegation in jQuery:

 

$( "#parent" ).on( "click", "li", function( event ) {
    // here your code
});