Etch-aSketch: onmouseover event is added to div, but does not work


#1

I’ve added the onmouseover event to my matrix of square divs. When I open the dev tools, I can see that the listener is added, and there are no JavaScript errors in the console. However, nothing changes on the squares when I mouse over them. Do you folks have any ideas as to why my code (below) is not working as intended?

Thanks in advance!

Edit: I haven’t fixed the problem, but I think I have it narrowed down to something more precise. The function called “activate” is not running. I placed a console.log in the function to test it, and nothing is logged in the console.

My JavaScript:

const container = document.getElementById(`container`);

let square;

for (i = 0; i < 256; i++) {
    square = document.createElement(`div`);
    square.setAttribute(`class`, `square`);
    square.addEventListener("onmouseover", activate);
    container.appendChild(square);
}

function activate() {
    square.style.backgroundColor = "gray";
}

#2

Your activate function references square which you keep changing. There is on way it knows which square you are referencing.

Try removing the let square line and then doing the following. Here we are block scoping each square and then passing a reference to that specific square to the mouseover function. As you need to pass the square as an argument I’ve nested it in an anonymous function.

for (i = 0; i < 256; i++) {
    const square = document.createElement(`div`);
    square.setAttribute(`class`, `square`);
    square.addEventListener("onmouseover", function() {
         activate(square);
      });
    container.appendChild(square);
}

function activate(square) {
    square.style.backgroundColor = "gray";
}

#3

Thanks so much for your help! Your solution definitely worked. I had to make one more correction, though. I was using the “onmouseover” event listener. I first tried your solution, and it still had some of the same symptoms as before. When I change it to just “mouseover” and implement your recommendation it works as intended.

I must admit that I do not understand fully why the anonymous function is needed, but I can at least remember to use it for event listeners in the future. Thanks again for your help!

Here’s my corrected code for reference:

const container = document.getElementById(`container`);

for (i = 0; i < 256; i++) {
    const square = document.createElement(`div`);
    square.setAttribute(`class`, `square`);
    square.addEventListener(`mouseover`, function () {
        activate(square);
    });
    container.appendChild(square);
}

function activate(square) {
    square.style.backgroundColor = `gray`;
}