Event Delegation in javascript

Event Delegation in javascript

What is Event Delegation ?

We can say that Event Delegation is a method of handling events for multiple HTML elements via a single event listener on their parent element. It is only possible because of how events propagate up to the hierarchy on the DOM tree.

Essentially the child elements events will bubble up via Event Bubbling to the parent element and trigger its event listener and then perform some action on the child element via the event.target

At the first, we will see our traditional way of attaching event listeners to HTML elements and then we can see how event delegation helps us to avoid the use of multiple event listeners

Traditional Example :

<ul id="animals">
  <li id="cow" name="cow" class="animal" >cow</li>
  <li id="tiger" name="tiger" class="animal" >tiger</li>
  <li id="lion" name="lion" class="animal" >lion</li>
</ul>

So in this example how we can add event listeners to all li tags ? one simple way is to select them by document.getElementById and then add event listeners to them separately

document.getElementById('cow').addEventListener('click', (e)=>{
    console.log(e.target.name, "clicked");  // cow clicked
})

document.getElementById('tiger').addEventListener('click', (e)=>{
    console.log(e.target.name, "clicked");  // tiger clicked
})

document.getElementById('lion').addEventListener('click', (e)=>{
    console.log(e.target.name, "clicked");  // lion clicked
})

Yessss ! we achieved what we wanted.

BUT Always remember every event handler in javascript is expensive

so to avoid this we use Event Delegation In Event Delegation, we will add only a single event listener to their parent element and use that single event listener to handle all of its child lets see an example which will give you a clear idea about it.

Event Delegation Example :

document.getElementById('animals')
    .addEventListener('click', event => { 
      if (event.target.className === 'animal') { 
        console.log(e.target.name, "clicked");
     }
});

this is how we can use event delegation to avoid multiple event listeners. We can also use event delegation to change the behavior of selected elements with special attributes like data attribute

Little glimpse about data attributes :

  • The data attribute name must start with "data-"
  • The attribute name should not contain any uppercase letters
  • Data attribute's name length must be at least one character long after the prefix "data-"
  • The stored data can then be used in the page's JavaScript to create a more engaging user experience (without any Ajax calls or server-side database queries).

let's see an example of this data attribute and see how data attribute and event delegation combiningly works in javascript.

<div id="inputform">
  <input type="text" id="firstname" data-uppercase/>
  <input type="text" id="lastname" data-uppercase/>
  <input type="email" id="email" />
</div>

// Javascript

document.getElementById('inputform')
    .addEventListener('change', event => { 
      if (event.target.dataset.uppercase != undefined) { 
        e.target.value === e.target.value.toUpperCase()
     }
});

this is an example of how data attribute and event delegation works combiningly and help us achieve what we wanted in a lesser line of code. in this code whatever we type in the first two input boxes it will automatically be converted into uppercase. if you want to add this functionality in some other input tag in the same parent div you just need to add data-uppercase attribute in that input tag and that's all it will work like charm

So why use Event Delegation ?

  1. We only need one event listener.
  2. Write less line of code
  3. Save memory as we will use only single event listener

So guys this is a short introduction to Event delegation. If you still have any questions regarding the event delegation please write a comment below!

Thank You ! I'll see you in the next blog

Have a nice day! ๐Ÿ˜‰

ย