Help using event listeners (Etch-a-sketch)


#1

I am working on the etch-a-sketch project right now and I want to use an event listener to call my paintSquare function on a mouseover event. This is the loop I wrote for adding a mouseover listener to each grid square.

for (let i = 0; i < gridSquares.length; i++) {
	id = 'box' + i;
	gridSquares[i].addEventListener('onmouseover', paintSquare(id));
}

When this loop runs, it paints all squares immedately. It does not wait for a mouseover event. What is causing it to do that?


#2

maybe because a loop is to iterate and it won’t wait for your mouseover
why not just try :
element.addEventListener(‘mouseover’, function(e){
e.target.style.backgroundColor = ‘grey’
})


#3

I found using assigning all the boxes to a variable using querySelectorAll, then using .forEach to add the listeners worked pretty well. having it as a variable lets you do the later steps involving changing what happens on mouseover a lot easier.


#4

maybe because a loop is to iterate and it won’t wait for your mouseover
why not just try :
element.addEventListener(‘mouseover’, function(e){
e.target.style.backgroundColor = ‘grey’
})

I’m not sure I understand. Wouldn’t my loop iterate through the nodelist gridSquares and add an event listener to each of those nodes? I notice that I forgot to include the code that declares gridSquares, but it’s the following in case that changes anything.

const gridSquares = document.querySelectorAll('.grid-square');

Could you tell me what your code would do differently? Assume I have the intellect of a small child because this is passing over my head so far.

I found using assigning all the boxes to a variable using querySelectorAll, then using .forEach to add the listeners worked pretty well. having it as a variable lets you do the later steps involving changing what happens on mouseover a lot easier.

Is the line I posted above what you’re talking about? I didn’t include all the relevant code in my initial post, sorry about that. I haven’t used .forEach before. Would that be done like this?

const gridSquares = document.querySelectorAll('.grid-square');
gridSquares.forEach(addEventListener('onmouseover', paintSquare()));

#5

try
gridSquares.forEach( square => { square.addEventListener( ‘mouseover’ , paintSquare) } )


#6

The issue is that you call paintSquare ^^ with parens, that calls the function as soon as JS parse the file and assigns the result of that to the event listener.

You would be better off doing as the above states. Then in the function you call you take an argument for the event which is passed by all event listener callbacks.

gridSquares.forEach( square => { square.addEventListener( ‘mouseover’ , paintSquare) } )

function paintSquare(e)  { //e here is passed by the event listener callback
  e.target // will give you the element the event listener was trigger on
}

You should be able to target the square that way.


#7

Thank you! I am finally starting to figure it out now.