2

I want to add a MouseOver effect for all my child items in my parentDiv. But now if I hover my mouse over one of those squares always the last of my childDivs actually changes its background, no matter on which child I place my mouse. Why is that?

for (let i = 0; i < Number(height); i++)
    {
        for (let j = 0; j < Number(width); j++)
        {                               
            var childDiv = document.createElement("div");
            childDiv.className = "childDiv";
            childDiv.style.backgroundColor = "#e6e6e6";
            childDiv.id = `${i};${j}`
            childDiv.onclick = () => childDiv.style.backgroundColor = "black";
            childDiv.onmouseenter = () => childDiv.style.background = "#cccccc";                
            childDiv.onmouseleave = () => childDiv.style.background = "#e6e6e6";
            parentDiv.appendChild(childDiv); 
        }           
    }

1 Answers1

1

Change var to let:

let childDiv = document.createElement("div");

working example here. And here is more info about differences between var and let (in short var childDiv is create once on first iteration (and visible outside for loops) and at the last iteration its value is set to last item - each arrow function ()=>{} use that childDiv and its last value after loop execution ; let childDiv is created on each iteration "separately" (it is not visible outside for loop) and pass to arrow functions ) .

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345