Shreya Joshi

Shreya Joshi

1571298507

Understanding Event Delegation in JavaScript

In this article, I’ll discuss how you, as a web developer, can optimize the addition of event listeners in all these situations by employing a technique called event delegation.

Event Delegation

Generally, on our webpage, we have a lot of events that handle everything, like click, keyup, input, mouse events, a lot of random events.

When our application grows, we need to add more events if we are following the same approach, and then the number of events keeps increasing and our web app keeps getting loaded with lots of events handlers.

At some point in time, it causes performance issues and our web app will be slower.

For example:

Suppose we have a webpage with five categories and all five categories are attached with event handlers. When we clicked on a category then an alert box will be opened with information. We can perform anything on this click, like redirecting to a separate webpage, console, call a function, etc.

Let’s see the code implementation for the above scenario. Write the below code in a file index.html and open it in the browser.

index.html:

<!DOCKTYPE HTML>
<html>
  <head>
    <title>Event Bubbling</title>
  </head>
  <body>
    <div class="container">
      <ul id="fruits">
        <li id="apple">Apple</li>
        <li id="banana">Banana</li>
        <li id="guavava">Guavava</li>
        <li id="greps">Greps</li>
       <li id="orange">Orange</li>
    </ul>
  </body>
  
  <script>
    // Bind an event listener for apple.
    var apple = document.querySelector('#apple');
    apple.addEventListener('click', (event) => {
      console.log("Apple clicked");
      alert("Apple clicked");
    });
    // Bind an event listener for Banana.
    var apple = document.querySelector('#banana');
    apple.addEventListener('click', (event) => {
      console.log("Banana clicked");
     alert("Banana clicked");
    });
    // Bind an event listener for Guavava.
    var apple = document.querySelector('#guavava');
    apple.addEventListener('click', (event) => {
      console.log("Guavava clicked");
      alert("Guavava clicked");
    });
    // Bind an event listener for Greps.
    var apple = document.querySelector('#greps');
    apple.addEventListener('click', (event) => {
      console.log("Greps clicked");
      alert("Greps clicked");
    });
    // Bind an event listener for orange.
    var apple = document.querySelector('#orange');
    apple.addEventListener('click', (event) => {
      console.log("Orange clicked");
      alert("Orange is 250/- per KG");
    });
  </script>
</html>

Let’s open this file in the browser:
This is image title

Great, it works fine… But what is the problem in our above code?

There is no problem in our code, but the problem is that we have five <li> elements and we have attached five event handlers to it.

What if, in the future, our categories increase to N? Will we write N event handlers?

Also in this code:

  • Can we remove some code?

  • Can we remove some event handlers and achieve what we want?

  • Can this task be done by writing less code instead?

  • Can we optimize the code?

The answer is: “Yes, we can.” We can write less code and achieve what we want by using event delegation.

Event delegation is, instead of attaching event handlers to each and every child element or the HTML elements individually, we will attach an event directly to its parent element. So, due to event bubbling in JavaScript, this is possible, event delegation can be done.

What will be the change after attaching the event to its parent element? The event happening is that the child element will propagate (bubble up) to its parent and the attached event handler of the parent will listen and the handler function will be invoked.

Let’s implement this into our code. We will make some changes to our index.html, so now our index.html will have the following code:

<!DOCKTYPE HTML>
<html>
  <head>
    <title>Event Delegation</title>
  </head>
  
  <body>
    <div class="container">
      <ul id="fruits">
        <li id="apple">Apple</li>
        <li id="banana">Banana</li>
        <li id="guavava">Guavava</li>
        <li id="greps">Greps</li>
        <li id="orange">Orange</li>
      </ul>
    </body>
  <script>

    // Bind an event listener to parents which is fruits.
    var apple = document.querySelector('#fruits');
    apple.addEventListener('click', (event) => {
      console.log(event.target.id + " clicked");
      alert(event.target.id + " clicked");
    });
  </script>
</html>

Now, we can see in the above code that I have removed all the event handlers from the previous code and written just one event handler to the parent element, which is fruits.

And this event handler does the same things that all five previous handlers were doing separately.

Let’s open this file (index.html) in the browser and see the result.

This is image title
Optimized ( event delegation ) code execution

This is how we can optimize our code using event delegation and improve code quality.

Pros and Cons of Event Delegation

Pros

  • Code quality: We can improve our code quality and maintenance would be easy.

  • Memory: Having more events in our code will take a lot of memory, and using event delegation we will save memory.

  • Performance: The event delegation will improve the performance of the app.

  • DOM manipulation: If we implement the event handlers on each and every child element and we have infinite scroll, then every time the child element gets added dynamically, the DOM will update every time. Using event delegation, DOM manipulation will be less.

Cons

  • Not all events bubble up. There are some events that are not bubbled up like blur, focus, window resizing, or scrolling. In this case, using event delegation would be tough.

  • The child stops propagation. Sometimes, HTML elements stop doing event propagation using stopPropagation(). In this case, the event propagation will be stopped and will not be bubbled up in the hierarchy.

Conclusion

The conclusion is that we need not attach event handlers to all the child elements. Instead, we can attach only one event handler to its parent and handle the function for achieving the goals.

Learn More

Thanks for reading.

#javascript

What is GEEK

Buddha Community

Understanding Event Delegation in JavaScript
Abigail  Cassin

Abigail Cassin

1594254111

The Art of JavaScript Event Delegation

JavaScript events are the catalysts behind most web functionality. Interacting with literally any website means firing away a ton of events. Have you ever thought about how these events get assigned? Are developers just tirelessly adding event functionality to every single element? What about dynamically created content, how do events get added to that? Well, there are a few different approaches to address these questions.

Nested Event Listeners

One approach is to assign an event listener every single time an element is created.

For our example code we will be creating buttons and adding event listeners to them. **Our goal is to change the colors of individual buttons on click. **Our starter HTML is just this:

<ul id="button-container">

</ul>

In our JavaScript file, we will be selecting the container, adding buttons to it by iterating over an array of colors, and appending each one to the container. This is arbitrary and just intended to mimic creating elements dynamically based on incoming data.

#event-delegation #javascript #javascript-events

Niraj Kafle

1589255577

The essential JavaScript concepts that you should understand

As a JavaScript developer of any level, you need to understand its foundational concepts and some of the new ideas that help us developing code. In this article, we are going to review 16 basic concepts. So without further ado, let’s get to it.

#javascript-interview #javascript-development #javascript-fundamental #javascript #javascript-tips

Rahul Jangid

1622207074

What is JavaScript - Stackfindover - Blog

Who invented JavaScript, how it works, as we have given information about Programming language in our previous article ( What is PHP ), but today we will talk about what is JavaScript, why JavaScript is used The Answers to all such questions and much other information about JavaScript, you are going to get here today. Hope this information will work for you.

Who invented JavaScript?

JavaScript language was invented by Brendan Eich in 1995. JavaScript is inspired by Java Programming Language. The first name of JavaScript was Mocha which was named by Marc Andreessen, Marc Andreessen is the founder of Netscape and in the same year Mocha was renamed LiveScript, and later in December 1995, it was renamed JavaScript which is still in trend.

What is JavaScript?

JavaScript is a client-side scripting language used with HTML (Hypertext Markup Language). JavaScript is an Interpreted / Oriented language called JS in programming language JavaScript code can be run on any normal web browser. To run the code of JavaScript, we have to enable JavaScript of Web Browser. But some web browsers already have JavaScript enabled.

Today almost all websites are using it as web technology, mind is that there is maximum scope in JavaScript in the coming time, so if you want to become a programmer, then you can be very beneficial to learn JavaScript.

JavaScript Hello World Program

In JavaScript, ‘document.write‘ is used to represent a string on a browser.

<script type="text/javascript">
	document.write("Hello World!");
</script>

How to comment JavaScript code?

  • For single line comment in JavaScript we have to use // (double slashes)
  • For multiple line comments we have to use / * – – * /
<script type="text/javascript">

//single line comment

/* document.write("Hello"); */

</script>

Advantages and Disadvantages of JavaScript

#javascript #javascript code #javascript hello world #what is javascript #who invented javascript

Peyton  Ullrich

Peyton Ullrich

1626016680

Easiest Series For Learning Javascript - Javascript Events - Video 15

Read more about javascript events here -https://www.w3schools.com/js/js_events.asp

#javascript #learning javascript #javascript events

Gaurav Sen

Gaurav Sen

1622696775

Understand JavaScript Event Listeners

You will be using events in almost every web app that you build. Therefore it is important to understand the basics of JavaScript events.

Understanding JavaScript Event Listeners

After watching this video you will have an understanding of event listeners - how to add them, remove them. Grasp advanced concepts such as bubbling and capturing. What is the event object? How does event propagation occur and how prevent the default behaviour of an event.

#javascript #event #event-listener #html5 #dom #web-development