0

I get stuck with a multiple click counter, that I'm trying to build in a dynamic way in pure javascript...here is my function

function createDivs(elements) {
  this.elements = [...elements]
  var count = 0

  for (var i = 0; i < elements.length; i++) {
    var div = document.createElement("div");
    div.setAttribute("id", elements[i]);
    document.body.appendChild(div);
    var p = document.createElement("p")
    p.setAttribute("id", elements[i].slice(0, -1))
    for (var j = 0; j < 2; j++) {
      var btn = document.createElement("button")
      btn.setAttribute("id", j % 2 === 0 ? "btn-sum-" + elements[i] : "btn-sub-" + elements[i])
      btn.innerHTML = j % 2 === 0 ? elements[i] + " +" : elements[i] + " -"
      div.appendChild(btn)
    }

    div.appendChild(p)
    var displayCount = document.getElementById(elements[i].slice(0, -1))
    var btnSum = document.getElementById("btn-sum-" + elements[i])
    var btnSub = document.getElementById("btn-sub-" + elements[i])
    console.log(displayCount)

    btnSum.addEventListener('click', e => {
      displayCount.textContent = count += 1
      return count
    }, false)

    btnSub.addEventListener('click', e => {
      if (count === 0) {
        return
      } else {
        displayCount.textContent = count -= 1
      }
      return count
    }, false)
  }
}

I know it looks awful..I'll break it in parts... but for now I just have this. The main idea is that each button have an independent count in the screen..but instead the result is that display one 0 and execute the event of the three buttons there.

you can call the function like this: createDivs(["count1","count2","count3"])

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • The `count` is scoped to the `createDivs` function. Everything inside that function is going to share that same variable. – Taplar Jan 13 '20 at 23:52
  • 1
    The return value of event listeners isn't used, there's no point to `return count`. – Barmar Jan 14 '20 at 00:10
  • 1
    You can put `let count = 0` into the `for` loop so that each iteration gets its own `count` variable. Or you could put the count in an attribute of the button instead of using a variable. – Barmar Jan 14 '20 at 00:12
  • All variables that are declared with `var` are shared by all the buttons, so they all update the same `displayCount` element. Use `let` to declare variables that are scoped to the `for` loop iteration. – Barmar Jan 14 '20 at 00:13
  • Using `let count = 0` inside the `for` loop works, in fact I'd changed all `var` keyword for `let` to get it working, thanks! – Santiago Spinetto Jung Jan 14 '20 at 00:42
  • Also, don't forget to use unique IDs. This line is creating duplicated IDs for each `

    ` tag: `p.setAttribute("id", elements[i].slice(0, -1))`

    – Bruno Monteiro Jan 14 '20 at 01:09

0 Answers0