• Home
  • Categories
  • Video Tutorials
    • Angular 5
  • News
  • About us
  • Contact us
  • Login
test
Code4Developers

Code4Developers

Code4Developers
  • Home
  • Categories
  • Video Tutorials
    • Angular 5
  • News
  • About us
  • Contact us
  • Login
  • JavaScript

Event Delegation in JavaScript

  • Yatendrasinh Joddha
  • April 19, 2018
  • 2 minute read
javascript
Total
0
Shares
0
0
0

Event delegation is a pattern of adding an event listener to a parent node instead, of adding an event listener to the individual node. The added event listener will check for the bubbled event to find matching child element. In this article we will talk about how to implement an event listener using very trending method in JavaScript i.e., event delegation pattern.

Let us consider an example where we have ‘ul’ which contains multiple ‘li’ of animals.

<ul id='animals'>
    <li id='animal1'>Lion</li>
    <li id='animal2'>Tiger</li>
    <li id='animal3'>Jaguar</li>
    <li id='animal4'>Leopard</li>
    <li id='animal5'>Cheetah</li>
</ul>

 

Now, here we want to perform an action when we click on the animal (li). As a developer first thing we do is adding an event listener to each ‘li’ and perform whatever action needs to be performed as below.

document.getElementById('animal1').addEventListener('click',function(){
  console.log('animal1');
});

There is nothing wrong with above method, it will work awesome but but but…. What if list is dynamic, and we need to add or remove some of the animals from the list?

We will do it, and we will also add and remove the list values and their associates event listener. But adding hundreds of event listeners is really a bad idea. This way of adding an event listener will also cause a memory leakage issue and will degrade the performance of your code.

What’s the Solution?

Solution is simple, add an event listener to the parent ‘ul’. But after adding a listener to the ‘ul’ how to find which ‘li’ is clicked?

Again, answer is simple: When event is bubbled up to the ‘ul’ element, you can check the target property of your object and it will help you to get which ‘li’ is clicked from the list. If you want to read more about event bubbling and capturing than do visit my previous article here at: https://code4developers.com/event-capturing-bubbling-javascript/

Please consider below code to achieve what we have talked so far.

document.getElementById("animals").addEventListener("click", function(e) {
  if(e.target && e.target.nodeName == "LI") {
  console.log(e.target.innerText);
 }
});

In above code we are adding event listener to parent element ‘ui’. When the event will be fired we will check the clicked element is ‘LI’ which we can check using ‘e.target.nodeName’. If it is ‘LI’ we are done.

Summary

Most of the developers uses JavaScript library and frameworks like JQuery, AngularJs for their DOM element and event handling. I recommend all of you to use event delegation methods your library or framework is providing. They provide advanced delegation and element identification.

What to read next…

  • Event Capturing and bubbling in JavaScript

  • What’s new in ECMASCRIPT 2018?

Yatendrasinh Joddha
Yatendrasinh Joddha

I have healthy knowledge and experience in Azure, O365 and ASP.Net with c#, MVC, WebApi along with client-side frameworks and libraries like JavaScript, JQuery, KnockoutJs, AngularJs, Angular, ReactJs, NodeJs

Views: 6,702

Share this:

  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on WhatsApp (Opens in new window) WhatsApp
  • Click to share on LinkedIn (Opens in new window) LinkedIn
  • Click to share on X (Opens in new window) X
  • Click to share on Pinterest (Opens in new window) Pinterest
  • Click to email a link to a friend (Opens in new window) Email
  • Click to print (Opens in new window) Print

Like this:

Like Loading...

Related Posts

Total
0
Shares
Share 0
Tweet 0
Pin it 0
2 comments
  1. Anonymous says:
    April 20, 2018 at 1:26 am

    Simple but very important one. Event should be handled properly.

    Reply
  2. Anonymous says:
    April 25, 2018 at 2:19 pm

    Content is very easy to understand. Good website to learn advance technologies

    Reply

Leave a ReplyCancel reply

Subscribe to Website via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Recent Posts
  • React Hooks Guide: Top Tips for Optimizing Performance in Your React Applications

    React Hooks Guide: Top Tips for Optimizing Performance in Your React Applications

    1 year ago
  • Demystifying JavaScript Tree Shaking: Boosting Performance and Reducing Bundle Size

    Demystifying JavaScript Tree Shaking: Boosting Performance and Reducing Bundle Size

    2 years ago
  • Unlocking the Power of React Hooks: A Comprehensive Guide with Examples

    Unlocking the Power of React Hooks: A Comprehensive Guide with Examples

    2 years ago
  • Celebrating a Decade of Phenomenal Growth: Insights and Reflections on 10 Years of Software Engineering

    Celebrating a Decade of Phenomenal Growth: Insights and Reflections on 10 Years of Software Engineering

    2 years ago
  • Angular Custom Elements: Creating Reusable Components with Angular

    Angular Custom Elements: Creating Reusable Components with Angular

    2 years ago
  • Connect Firebase Realtime NoSQL Database with Angular App from Scratch

    Connect Firebase Realtime NoSQL Database with Angular App from Scratch

    5 years ago
  • How to Build an Inclusive Esports Community

    How to Build an Inclusive Esports Community

    5 years ago
  • Best Digital Icebreakers

    Best Digital Icebreakers

    5 years ago
  • Email alerts when a docker container stopped in AWS ECS CLUSTER

    Email alerts when a docker container stopped in AWS ECS CLUSTER

    5 years ago
  • New Learning Models for Fall 2020

    New Learning Models for Fall 2020

    5 years ago
Subscribe to Website via Email

Enter your email address to subscribe to this website and receive notifications of new posts by email.

Featured Posts
  • javascript 1
    Spread syntax (three dots) in JavaScript
    • March 21, 2018
  • Angular 2
    Angular 6 CRUD – Part 1: Project Setup, Routing, Service
    • May 9, 2018
  • javascript 3
    Local Storage and Session Storage
    • May 22, 2017
  • Angular 4
    Angular 4 Project Structure
    • June 18, 2017
  • AWS 5
    Email alerts when a docker container stopped in AWS ECS CLUSTER
    • July 24, 2020
Code4Developers
Learning is never ending process

Input your search keywords and press Enter.

%d