How to define EventListener for dynamic elements created in javascript

JavaScript makes it possible to execute functions when a certain event occurs within the DOM of our HTML. This event can be a “click” on a certain element (usually a button), the selection of an “option” within a combo, or even the loading (load) of the page.

In addition, another interesting and widely used feature in JavaScript is the possibility of creating elements (inputs, divs, links or any other type of HTML component) dynamically (also through events).

In order to execute a certain function after the occurrence of an event, we need to define it (add) in the component’s “EventListener”. In the following example I show a simple HTML document (index.html), which has:

  • a button to add elements (new “buttons”) dynamically
  • the static “Button 1”, which is already displayed by default on the page

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>rafaelWendel.com</title>
    <style>
        .btn {
            display: block;
            margin-bottom: 10px;
        }
    </style>
</head>
<body>
    <button id="btnAdd">Add button</button>
    <hr />
    <div id="btnList">
        <button class="btn">Button 1</button>
    </div>
    <script src="scripts.js"></script>
</body>
</html>

This file imports the file “scripts.js”, which is where we implement the codes to create new elements (buttons) dynamically.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
var counter = 1;
 
function addNewButton()
{
    counter++;
    //create a new element
    let newButton = document.createElement('button');
 
    //define the "btn" class
    newButton.classList.add('btn');
 
    //define the button text
    newButton.innerText = "Button " + counter;
 
    //add the new element to "btnList" div
    document.getElementById("btnList").append(newButton);
}
 
window.onload = function(){
    //define the EventListener to the "btnAdd" click
    let btnAdd = document.getElementById('btnAdd');
    btnAdd.addEventListener('click', addNewButton);
 
    createBtnEventListener();
}

The “addNewButton” function creates an element dynamically and inserts it (append) into the div “btnList”. This function will be called (executed) whenever the “btnAdd” button is clicked (defined in line 22). Note that all the new buttons that are created, have the class “btn” (line 10).

Executing this “index.html”, and clicking “btnAdd” 3 times, we have the following result.

Image 1: Running the file “index.html” and creating 3 new buttons dynamically

So far everything is quiet. We define an action for when the “btnAdd” click event occurs. But, what if we want to define an action for when one of the “btn” buttons is clicked. For example, when you click on one of the buttons that were generated dynamically, it displays an alert with the text of the respective button.

This procedure is also relatively simple. But we have to understand 2 things

  • we need to define the EventListener for a set of elements that have the same class (class “btn”)
  • whenever a new element is created dynamically, we have to define the EventListener for the elements of the class again (since this new element also needs to have its click action defined =)

So, in my “scripts.js” file, I created 2 new functions: “alertBtn” (line 22) and “createBtnEventListener” (line 28).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
var counter = 1;
 
function addNewButton()
{
    counter++;
    //create a new element
    let newButton = document.createElement('button');
 
    //define the "btn" class
    newButton.classList.add('btn');
 
    //define the button text
    newButton.innerText = "Button " + counter;
 
    //add the new element to "btnList" div
    document.getElementById("btnList").append(newButton);
 
    //call the function to refresh the EventListener
    createBtnEventListener();
}
 
function alertBtn()
{
    let msg = this.innerText;
    alert(msg);
}
 
function createBtnEventListener()
{
    //get all ".btn" elements (in array format)
    let btn = document.querySelectorAll('.btn');
    for(let item of btn){
        item.addEventListener('click', alertBtn);
    }
}
 
window.onload = function(){
    //define the EventListener to the "btnAdd" click
    let btnAdd = document.getElementById('btnAdd');
    btnAdd.addEventListener('click', addNewButton);
 
    createBtnEventListener();
}

The function “createBtnEventListener” is responsible for creating the EventListener of all buttons with class “.btn” that exist in the document. All of these buttons are returned in an “array” format (line 31) and I need to scroll through this array to be able to define the EventListener one by one.

Finally, see that this function is called at 2 different points:

  • The moment the page is loaded for the first time (line 42, inside window.onload),
  • Within the “addNewButton” function. It is called here, so that the new elements (buttons) created dynamically (after the page loads) also work.

So, after creating some elements dynamically, and clicking on “Button 3”, we have the following result:

Image 2: Executing the action of a dynamically created element

I hope you enjoyed this content.

Hugs!

Holds a university degree in Information Systems, a postgraduate degree in Database Systems and a master's degree in Education with a focus on Sociocommunity Technologies. He works as a professor of technical and technological education at the Federal Institute of Education, Science and Technology of São Paulo, teaching subjects in the areas of programming, database, project development and software engineering.

Posts relacionados

Leave a Reply

Your email address will not be published.