Using addListener to an element that would be created later

Tags:



I get an error ‘.addListener is not a function’ upon trying this:

if(document.getElementById("id")){
   document.getElementById("id").addListener('click', function(){alert("ok");});
}

This element ‘id’ comes into picture when the entire document gets loaded, and I am using it in the middle of the documents construction. So, I did this:

window.onload = function(){
                if(document.getElementById("id")){
                   document.getElementById("id").addListener('click', function(){
                   alert("ok");
                   });
                }
}

The error is gone now, but the element ‘id’ does nothing upon being clicked.
How to make it clickable?

Answer

It sounds like you may be assigning to window.onload more than once. If you do this, only the last callback assigned to it will run. Use addEventListener instead, so that prior assignments to onload do not conflict with later assignments to onload.

You can also listen for DOMContentLoaded instead of load, allowing the listener to be attached faster:

window.addEventListener('DOMContentLoaded', function(){
  const elm = document.getElementById("id");
  if(!elm){
    return;
  }
  elm.addEventListener('click', function(){
    alert("ok");
  });
});

Best to never assign to an .on- property unless you’re certain it will never be assigned to again (or unless you’re certain it should only ever have one listener).



Source: stackoverflow