Guvi-blog-logo

Event Binding On Dynamically Created Elements

event binding on dynamically created elements in JavaScript

Event binding on dynamically created elements is one of the most searched queries by JS users. Being a javascript user, you all might have heard about the event in JS. But do you actually know that javascript has provided various event handlers to make your work easier?

Onclick, OnChange, OnDblClick, and more are some of the event handlers. Apart from this, with the help of event binding, you can actually add any event handler for performing a particular event. 

If you are one of the users who is facing an issue with event binding. This blog is for you. I have detailed all the major points and examples for a better understanding. 

But before moving to the solution for event binding on dynamically created elements, let’s get a short overview of event handling and event binding.

Master JavaScript and Ace your Web Development Career: 6 Best Front End JavaScript Frameworks to Learn in 2021

What is Event handling?

Whenever there is a change in the object’s state, it is termed an Event. On the other hand, the reacting process on the event is known as Event Handling. 

What is Event binding?

Using the event binding, a user can add any event handler. After adding the event handler, the selected JS function will invoke at the time the event is triggered. This triggered event is associated with the specific DOM (Document Object Model) elements. 

Note: JS users can bind to an event like mouseover, mouseout, and keypress.

Now, let’s check the solutions for event binding on dynamically created elements.

What would be the best solution(s) for event binding on dynamically created elements?

event binding in JavaScript to dynamic elements

You might have noticed that I am using the word “solution(s)” for event binding. 

Why? 

Is there any problem for which we actually try to find the solutions?  

Yes, there is!!! So, what is the problem?

Well, it has been noticed that many JS users use looping and binding the event to the loop. It works fine. But sometimes, when users select the boxes/button(s) that are added with DOM or Ajax, it does not have any event bound after the initial loop.

To solve this kind of issue, several other JS users suggest using different plugins. But I have the best solution that works without any plugin. The solution is:

  • by using direct JavaScript code
  • by using the JS library like react.js, jquery, and others (but in this blog, I have discussed the jquery approach)

So, let’s begin with direct JS code.

Direct JS code approach

Here, our main objective is that, whenever the new event is added, it will move ahead and add the click handler to the particular element. For this, there is a simple way that is EVENT BUBBLING. 

Note: Event Bubbling is just as the sequence of calling the event handlers if the element is nested in the other elements. Now, both elements should have a registered listener for a similar event.

In this, JS users add the event listener to the element(s) in the DOM hierarchy’s higher level. But, you do not want to get the alert to get triggered for the overall action_1 div. 

So, how to fix this?

Here, we will add the test for ensuring that the alert performs. It will perform in the case when the clicked element would be the class of action_2.

Let’s take a look at the code:

<!DOCTYPE html><html lang=”en”>
<head>    <meta charset=”UTF-8″>    <meta http-equiv=”X-UA-Compatible” content=”IE=edge”>    <meta name=”viewport” content=”width=device-width, initial-scale=1.0″>    <title>code_1</title></head>
<body>
<div id=”action_1″>        <button class=”action_2″>Button 1</button>        <button class=”action_2″>Button 2</button>    </div>
    <script>        const box = document.querySelector(‘#action_1’);
        box.addEventListener(‘click’, function (e) {
            if (e.target.classList.contains(‘action_2’)) {                alert(e.target.innerHTML);            }        });
        const newBtn1 = document.createElement(‘button’);        newBtn1.classList.add(‘action_2’);        newBtn1.innerHTML = ‘Button 3’;        box.append(newBtn1);
    </script>
</body>
</html>

You can see that we have added the event listener to the overall box. And we only get the alert when the e.target.classList consists of action_2. It will work and show the output as:

RUN THE ABOVE CODE IN ANY OF THE IDE TO GET THE OUTPUT

Embed MP4 in HTML <img loading=

Using delegate() function of JQuery

JS users want to use the JS library for event binding on dynamically created elements. For this, they must go with the delegate() function of jquery. 

Note: The jquery’s delegate() method is useful for adding the single or multiple event handlers to the particular element. These elements can be the children of the chosen elements. They can also use for specifying the function to execute when the event occurs.

In delegate(), when the user clicks the new element, a similar action will be performed for each element. Moreover, it allows the user to add one event listener to the parent element.

Further, a similar action will be triggered for all the children elements. If you add the new element in the future, again the same action will be triggered for the new element.

Let’s take a look at the code:

<!DOCTYPE html><html lang=”en”>
<head>    <meta charset=”UTF-8″>    <meta http-equiv=”X-UA-Compatible” content=”IE=edge”>    <meta name=”viewport” content=”width=device-width, initial-scale=1.0″>    <title>code_2</title>
    <script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js”>    </script>
    <script>        $(document).ready(function () {            $(“#list”).delegate(“li”,                “click”, function (event) {
                    $(‘#list’).append(                        ‘<li> Point </li>’);                });        });    </script>
</head>
<body>    <ul id=”list”>
        <!– Click here –>        <li>Click here !!!</li>    </ul></body>
</html>

RUN THE ABOVE CODE IN ANY OF THE IDE TO GET THE OUTPUT

Now, the output shows that whenever the user clicks on any of the elements, the same action is preferred for each element.

This is how you can do event binding on dynamically created elements.

JavaScript Interviews can be way easier now: 42 JavaScript Questions Towards Better Interviews

Final Thought!!

Now, I have explained all the necessary solutions for event binding on dynamically created elements. Finally, I can say that you can get multiple solutions for event binding problems. 

Moreover, you can also use different frameworks of JS like reach.js, jquery, and more to solve this problem. If you want to know those methods in detail, let me know through your comments. 

Moreover, you can comment if you have any doubts about the above examples.

“Wish to learn JavaScript & other programming languages? Then stay tuned with us!”

Let’s test the knowledge you get from this blog!

  1. Which of these is the right event handler to identify a mouse click over a link?

(A) onLink

(B) onClick

(C) onMouseUp

(D) None of these

Correct Answer: (B)
The mouse click’s event handler is onClick.
  1. Event handler considers nothing but ______.

(A) Interface

(B) Handler

(C) Function

(D) Event

Correct Answer: (C)
The event handler is considered as the function in JavaScript.
  1. Answer whether the below statement is correct or not.

The addEventListener() method in JS enables users to set a function(s) to be called if a particular event occurs like in the case of the user clicking a button.

(A) True

(B) False

Correct Answer: (A)
Using addEventListener(), you can actually add the function(s) that called for the particular event.
  1. The delegate() method in JavaScript can attach single or multiple event handlers to the specified ______.

(A) Child element

(B) Element

(C) Child element and element

(D) None of these

Correct Answer: (A)
The delegate() method enables the JS user to attach single or multiple event handlers to the particular child element.
  1. Check whether the below statement is true or false.

The querySelectorAll() method is used for returning each element in the document. These elements will match a specified CSS selector(s).

(A) False

(B) True

Correct Answer: (B)
The above statement is true regarding the querySelectorAll().

So, we hope you are clear with the event binding concept in JavaScript. If you wish to learn JavaScript from the experts just check our 100% Placement assuring courses here-

Have further queries?

GUVI | C Programming course online

Let us know in the comment section below. You may fill out the below form and drop us your contact for a free talk with Industry Experts.

Contact Form

By clicking 'Submit' you Agree to Guvi Terms & Conditions.

Our Learners Work at

Our Popular Course

Share this post

Author Bio

GUVI Geek
GUVI Geek

Our Live Classes

Learn Javascript, HTML, CSS, Java, Data Structure, MongoDB & more
Learn Python, Machine Learning, NLP, Tableau, PowerBI & more
Learn Selenium, Python, Java, Jenkins, Jmeter, API Testing & more
Learn Networking, Security Testing, IAM, Access Management & more

Hey wait, Don’t miss New Updates from GUVI!

Get Your Course Now

Related Articles