0

I add an event listener to every div out of my gird of 100divs. In the function I should be passing as a parameter the square which is clicked. The problem is the click() function only recongnizes the last div (number 99).

function createBoard(){

 for(var i=0;i<width*height;i++){
 
  var square=document.createElement('div');
   grid.append(square);
   square.setAttribute('id',i);
   square.innerHTML=boardArray[i];
   squares.push(square);
   
   
    squares[i].addEventListener('click', function(e) {
    click(square)
  })

 }//end for 

                   }//end func

createBoard();




function click(square){
var id=square.id;
console.log(id) //displays 99th 

}
  • why not just `square.addEventListener('click', function(e) {click(square)});`, and also, append your squares after setting the traits of the squares – lionrocker221 Apr 28 '21 at 17:35
  • 2
    https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – epascarello Apr 28 '21 at 17:37

2 Answers2

1

You need to use const instead of var when defining square. It's a bit of javascript voodoo, but what's happening is when you define a variable with var it gets put in the scope of the function it's in, so that every iteration of the loop updates the reference in the square variable. const and let get put in the scope of the block that they are defined in, so each iteration will get their own square.

You could bypass the issue by having the event listener use event.target instead of square.

Charlie Bamford
  • 1,268
  • 5
  • 18
0

Why not pass i to the function if all you want is the id that you place on the div?

outworlder
  • 36
  • 5