1

In the code below I am getting an error that cannot change the background Color of undefined. When I replaced squares[i] with this code worked. I am not getting it Why?


var colors =[
    "rgb(255, 0, 0)",
    "rgb(255, 255, 0)",
    "rgb(0, 255, 255)",
    "rgb(0, 0, 255)",
    "rgb(0, 255, 0)",
    "rgb(255, 0, 255)"
];


var colorPicked = colors[3];
var head = document.querySelector("#color");
head.textContent = colorPicked;

var squares = document.querySelectorAll(".square");

for(let i=0;i<squares.length;i++){
    //to apply colors array on the square
    squares[i].style.backgroundColor = colors[i];

    //adding click event listener to square
    squares[i].addEventListener("click",()=>{
        var chosenColor = this.style.backgroundColor;
        if(chosenColor == colorPicked){
            alert("correct")
        }else{
            alert("wrong")
        }
    })

}

1 Answers1

1

Arrow function (=>) does not have its own this. Either use normal function syntax or use squares[i] inside the event handler function:

var chosenColor = squares[i].style.backgroundColor;
Mamun
  • 58,653
  • 9
  • 33
  • 46