Reputation: 173
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?
Upvotes: 0
Views: 156
Reputation: 370729
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).
Upvotes: 1
Reputation: 2861
Because the element is added later in the dom, you can not attach a listener this way. What you should do is to attach a listener on the document that will 'filter' the events, so elements added later on in the dom will still be able to fire your events. Try the code below:
document.addEventListener('click',function(e){
if(e.target && e.target.id== 'id'){
//do something
}
});
Now anytime anything is clicked on the dom, this listener will await for an element with id='id' to execute your code, otherwise it will not do anything. This method is called "event delegation", look it up for more info!
Upvotes: 1