Weber Weber - 11 months ago 54
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]; = userHeight; = userWidth; = "2px solid black";

for(i = 0; i < gridCount; i++) {
var gridSqr = document.createElement('div');
container.appendChild(gridSqr); = "inline-block"; = "16px"; = "16px"; = 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
's. What I am trying to do is be able to draw a bunch of
'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
so I so that the individual
'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 Source

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(){ = '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?