I was working on some code I wrote and I had this problem where an eventListener I added to a dynamically created element, but it does not "fire" aka work.
var eleButton = document.createElement("button");
eleButton.innerText="Post";
eleButton.type="submit";
...
eleButtonContainer.appendChild(eleButton);
And the eventlistener was a basic "click"
eleButton.addEventListener("click", function() {
console.log("Hello World");
});
That did not work, so i searched around and could not find any answers. I finally found a work around of using document and checking whether or not that element was check or not. So my resulting code became this:
var eleButton = document.createElement("button");
eleButton.innerText="Post";
eleButton.type="submit";
eleButton.id = "usrResponseSubmit";
console.log(eleButton);
document.body.addEventListener('click',function(){
if(event.target.id == "usrResponseSubmit"){
console.log("ok now it works");
}
});
This works fine, but it still makes me question about the code atop. I willing to take the "if it werks it works" route, but I would also still like to use the eleButton.addEventListener route because that was what I always used.
So my two questions are:
Before you say, but it works on my end, my code is kinda crap and long. Essentially, I have this eleButton nested in a container that is nested in a container ... (x~10-20). I don't think this is necessarily the problem. But I also have some other eventListeners that "may" overlay with eleButton. I'm not too sure that's the case as i've been trying and testing everything I can.
I have also pulled the eleButton and appended it to an existing object and the event did fire. Can someone give me a run down of when events do not fire?
Nothing is wrong with your code, maybe you just misspelled something. here i made a codepen example you can check.
html:
<div id="btnCon"></div>
...
JS:
const eleButtonContainer = document.querySelector('#btnCon')
var eleButton = document.createElement("button");
eleButton.innerText="Post";
eleButton.type="submit";
eleButtonContainer.appendChild(eleButton);
eleButton.addEventListener("click", function() {
console.log("Hello World");
});