0

When I click mt 'Easy' btn that supposed to give me an output of 3 colors, it give me six like my 'hard' btn (also in the console I get 6 colors.

Part of my JS:

var modeBtn = document.querySelectorAll(".mode");
for (var i = 0; i < modeBtn.length; i++) {
  modeBtn[i].addEventListener("click", function() {
    modeBtn[0].classList.remove("selected");
    modeBtn[1].classList.remove("selected");
    this.classList.add("selected");

    //The short way - This called "the ternary oprator"
    /*
        this.textContent === "Easy" ? numSquares = 3: numSquares = 6;
        */
    //The longer  Way
    if (this.textContent === "easy") {
      numSquares = 3;
    } else {
      numSquares = 6;
    }
  });
}
<div id="stripe">
  <button id="reset">New Colors</button>
  <span id="message"></span>
  <button class="mode">Easy</button>
  <button class="mode selected">Hard</button>
</div>

Here is my complete code at Codepen

1 Answers1

2

I debugged the code and found that the issue lies in the value of i in the method init().

Once the document is loaded, the init() method adds event listener to both the buttons, Easy & Hard. When the value of i becomes 2, the loop terminates.

When the button is clicked, and since i is declared as var, which creates a scope at the function level and not the block level, this.textContent actually tries to access the value of modeBtn[2] which is undefined.

So, the solution is to declare the variable i as let. This will definitely solve your problem.

Refer this link for more details.

Pranjal Successena
  • 907
  • 1
  • 11
  • 24