I'm doing a simple stopwatch in JS based on a tutorial I found online. I got the tutorial code working and then remade it my way. I added some things and found that my event listeners don't fire. Once I gave up on trying to figure out what causes the error I rewrote the program line by line and it worked fine. I then realised that I forgot one line and once I added it, I found the culprit.
The function just adds buttons to a div.
function appendButtons(container) {
container.appendChild(startButton);
container.appendChild(stopButton);
container.appendChild(resetButton);
}
If it's changed to this however, it stops the listeners on the buttons working.
function appendButtons(container) {
container.appendChild(startButton);
container.appendChild(stopButton);
container.appendChild(resetButton);
container.innerHTML += "<hr>";
}
Now, I know that I probably shouldn't have used innerHTML there, but it did put a hr on the page and I still don't know why this had any effect on the event listeners.
The function creating the buttons looks like this:
function createButton(name) {
var button = document.createElement("input");
button.type = "button";
button.value = name;
button.addEventListener("click", function(e) {
console.log("working");
});
}
BTW, I just changed the line to this and it works:
container.appendChild(document.createElement("hr"));
");` if you want to use HTML, and *never* use `+=` with `elem.innerHTML` again. – Nov 10 '15 at 00:55