0

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"));
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Yulek
  • 331
  • 3
  • 12
  • Possible duplicate of [Is it possible to append to innerHTML without destroying descendants' onclick functions?](http://stackoverflow.com/questions/595808/is-it-possible-to-append-to-innerhtml-without-destroying-descendants-onclick-fu) – Paul Roub Nov 10 '15 at 00:52
  • 2
    Short version: `innerHTML += "whatever"` means: 1. Get the current HTML 2. Append "whatever". 3. Empty the container of all its contents. Your handlers were attached to those contents. 4. Set the inner HTML to the new string, **recreating** elements as we go. – Paul Roub Nov 10 '15 at 00:53
  • `appendChild()` does none of those things. It adds an element, and is *definitely* what you want. – Paul Roub Nov 10 '15 at 00:54
  • 1
    Change it to `container.insertAdjacentHTML("beforeend", "
    ");` if you want to use HTML, and *never* use `+=` with `elem.innerHTML` again.
    –  Nov 10 '15 at 00:55
  • Nice. I didn't know innerHTML did that. Thanks for the help. – Yulek Nov 10 '15 at 01:01

0 Answers0