Search code examples
javascriptaddeventlistener

Javascript : how to re-attach the same event listener to a element reppeared?


In my code, I have a h1 container with h1 element inside like below :

<div id="container_h1"><h1 id="h1">Title H1</h1></div>

Then, I attach an event listener to h1 element in order to alert h1 text when the user clicks on h1 element :

var h1 = document.getElementById("h1");
h1.addEventListener(
                        "click", 

                        function()
                        {
                            alert(h1.innerHTML);
                        },

                        false                       
                    );

Then, I have 2 buttons for removing and inserting h1 element, like below :

<input type="button" value="remove H1" onclick="remove_h1();">
<input type="button" value="insert H1" onclick="insert_h1();">

//container_h1 element :
var container_h1 = document.getElementById("container_h1"); 

//Remove h1 :
function remove_h1()
{
    container_h1.innerHTML = "";    
}

//Re-appear h1 :
function insert_h1()
{
    container_h1.innerHTML = '<h1 id="h1">Title H1</h1>';   
}

The problem :

When I make disappear h1 element by clicking "remove H1" button then make reappear h1 element by clicking "insert H1" button, and then I click on h1 element, h1.addEventListerner in the code has no effect, no alert is triggered.

So how can I re-attach the same event listener to h1 element when this h1 element reappears ?

Thank you.


Solution

  • Instead of h1.addEventListener, use document.body.addEventListener:

    document.body.addEventListener('click', function(event) {
        if (event.target.nodeName == 'H1') {
            // your code
        }
    })
    

    So you bind event listener to body rather than h1. The thing is that your h1.addEventListener(...) is only applied on currently in DOM existing <h1> elements, but not on dynamically created ones.

    http://www.theappguruz.com/blog/dynamic-event-binding-demo-jquery

    How do I attach events to dynamic HTML elements with jQuery?