In my JavaScript code, I am creating a 16x16 grid of divs
. Each div
should change its background color from black to white when the mouse enters (inherited based on a common class).
However, I am facing an issue where all the divs
change color simultaneously when hovered over. Instead, each div
should change its own color individually.
I suspect that all events are referencing the final div
under the "squares" class, causing this unexpected behavior. I need help in making each event reference its respective div
.
SNAPSHOT https://i.sstatic.net/oKmWW.png
CODE
//GRID CREATION (30x30)
var container = document.getElementById('container');
var size = 30;
//Row Creation (30)
for(j=0; j < size; j++) {
var row = document.createElement('div');
row.classList.add("row");
//Square Creation (30 per Row)
for(i=0; i<size; i++) {
var square = document.createElement('div')
square.classList.add("square");
//div background-color changes on mouse-enter
square.addEventListener('mouseenter', () => {
this.square.style.background = 'white';
});
row.appendChild(square);
}
container.append(row);
}