Search code examples
javascriptif-statementclassname

if statement not executing action even though condition is met


I'm trying to change the class of an element based on some conditions.

const pwnButtonHidden = document.querySelector(".pwn-button-hidden");
let condition = 0;

for (let idNumber = 1; idNumber < 13; idNumber++) {
  setTimeout(() => {
    document
      .getElementById(`btn-${idNumber}`)
      .addEventListener("click", (e) => {
        condition++;
        console.log(condition);
        document.getElementById(`product-${idNumber}`).className =
          "product-fake";
        document.getElementById(`btn-${idNumber}`).disabled = true;
        document
          .getElementById(`btn-${idNumber}`)
          .removeEventListener("mouseenter", selectSfx, true);
      });
    if (condition >= 12) {
      pwnButtonHidden.className = "pwn-button";
    }
  }, 4000);
}

As you can see, at every click condition is augmented by 1. However, even when it reaches 12 (verified by console.log(condition)), it doesn't trigger the class change. How can I fix this?

Tried changing the number of the condition.


Solution

  • Testing the condition is happening outside of the click event handler. So it's only being checked one time for each loop iteration right when the 4 second delay times out. The code is relocated below.

    ...
            .removeEventListener("mouseenter", selectSfx, true);
          if (condition >= 12) {
            pwnButtonHidden.className = "pwn-button";
          }
          });
      }, 4000);
    }