1

What I'm trying to do here is to apply an eventListener to every element of one class, and then, after user clicked on one of those elements, he will be prompted dependent on the index of that element in the class array.

Also, yes, I know that it can be done in many different ways, but I want it to work in this particular one (if it is possible).

var buttons = document.getElementsByClassName("openbtn");
var i;
for (i = 0; i < buttons.length; i += 1) {
    buttons[i].addEventListener("click", function () {
        switchBtn(i);
    });
}


function switchBtn(index) {
    switch (index) {
    case 0:
        prompt("case0");
        break;
             
    case 1:
        prompt("case1");
        break;
             
    default:
        alert(index);
        break;
    }
}
  • By not working do you mean nothing happens when you click on buttons? – Skoua Dec 30 '20 at 15:09
  • Yes, nothing happened when I clicked on buttons, so I changed the let to var of confusion. The real problem was that the soft I was using to run my code did not support ES6, which is why the code was not working (took a while to figure out that) – Qwerty Uiop Dec 30 '20 at 21:58

1 Answers1

0

All the event handler functions share the same i variable, which is equal to buttons.length at the end of the loop, so the default case will be used each time. Instead, use let for lexical scoping.

var buttons = document.getElementsByClassName("openbtn");
for (let i = 0; i < buttons.length; i += 1) {
    buttons[i].addEventListener("click", function () {
        switchBtn(i);
    });
}


function switchBtn(index) {
    switch (index) {
    case 0:
        prompt("case0");
        break;

    case 1:
        prompt("case1");
        break;

    default:
        alert(index);
        break;
    }
}
<button class="openbtn">case 0</button>
<button class="openbtn">case 1</button>
<button class="openbtn">default</button>
Unmitigated
  • 76,500
  • 11
  • 62
  • 80