Weber Weber - 1 month ago 9
CSS Question

How would I get onmouseover() to work in my loop?

function genGrid(){
var gridCount = (userHeight/16) * (userWidth/16);
var container = document.getElementsByClassName('container')[0];
container.style.height = userHeight;
container.style.width = userWidth;
container.style.border = "2px solid black";


for(i = 0; i < gridCount; i++) {
var gridSqr = document.createElement('div');
container.appendChild(gridSqr);
gridSqr.style.display = "inline-block";
gridSqr.style.height = "16px";
gridSqr.style.width = "16px";
gridSqr.style.backgroundColor = userbgColor;

};
};


The function above uses some inputs from prompts (other functions that I didn't put here for brevity) to generate anywhere from 2-1000
<div>
's. What I am trying to do is be able to draw a bunch of
<div>
's as grid squares with a set background color. Then I want to be able to mouse over them and draw something with my mouse. Think Etch-E-Sketch. Problem is, I cannot figure out how to implement
.onmousenter()
so I so that the individual
<divs>
's will change color when I roll my mouse over them. I have tried a bunch of different way's but I am new to JS and I am not finding any success.

In short. I need to change background color on mouse enter, of the individual div's I create in this script.

I don't want to use JQuery

Answer

When you are looping, for each div you can use the .addEventListener() method.

Here is an example of the addEventListener method in action:

var etchASketch = document.getElementById('etchASketch');

etchASketch.addEventListener('mouseenter', function(){
  etchASketch.style.background = 'black';
});
#etchASketch {
  border: 1px solid black;
  height: 100px;
  width: 100px;
}
<div id='etchASketch'></div>

Edit: @Donald Wu I'm a new user but I thought that "copying, where appropriate and with correct attribution is explicitly encouraged on Stack Overflow". What is the point of copy and pasting the code from an earlier answer and resposting it? Isn't the outcome just two answers that have the same information?