I was using the "this" keyword here in my code and decided to replace that with squares[i]. As I click the div, my console is showing me error message: "Cannot read propery of undefined".
var colors=[
"rgb(255, 0, 0)",
"rgb(255, 255, 0)",
"rgb(0, 255, 0)" ,
"rgb(0, 255, 255)",
"rgb(0, 0, 255)",
"rgb(255, 0, 255)" ];
var squares=document.querySelectorAll(".square");
var pickedColor=colors[3];
var display=document.getElementById("colorDisplay");
display.textContent=pickedColor;
for(var i=0;i<squares.length;i++){
//ADD INITIAL COLORS TO SQUARES
squares[i].style.backgroundColor=colors[i];
//ADD EVENTLISTENERS TO SQUARES
squares[i].addEventListener("click",function(){
console.log(squares[i].style.backgroundColor);
});
}
//__________________________________________________________________________
//This is the correct version of the code
var colors=[
"rgb(255, 0, 0)",
"rgb(255, 255, 0)",
"rgb(0, 255, 0)" ,
"rgb(0, 255, 255)",
"rgb(0, 0, 255)",
"rgb(255, 0, 255)" ];
var squares=document.querySelectorAll(".square");
var pickedColor=colors[3];
var display=document.getElementById("colorDisplay");
display.textContent=pickedColor;
for(var i=0;i<squares.length;i++){
//ADD INITIAL COLORS TO SQUARES
squares[i].style.backgroundColor=colors[i];
//ADD EVENTLISTENERS TO SQUARES
squares[i].addEventListener("click",function(){
console.log(this.style.backgroundColor);
});
}
I have added two versions of the code. The first one is incorrect, while the second one is the correct one.