0

what i am trying to do is to have a n*m grid of elements and to change an Array when one of the elements is clicked.

Example:

2*2 grid

O O

O O

Array = [false,false,false,false] than i click on the second 0 and get Array = [false,true,false,false]

What i tried was something like this:

for (var i = 0; i < n; i++ ) { 
    for (var j = 0; j < m; j++) {
        
        Element.addEventListener('click', (event) => {
            Array [i][j] = true
        }
    }
}

Here i and j are always n and m what results in me only changing the last Element. How do i fix that?

mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • 5
    Change `var` -> `let` – VLAZ Apr 20 '21 at 08:30
  • 1
    Delegate. `document.getElementById("container").addEventListener("click",function(e) { const tgt = e.target; if (tgt.classList.contains("gridElement")) arr[tgt.dataset.row][tgt.dataset.col] = true; })` where you store the row and column in data-row and data-col – mplungjan Apr 20 '21 at 08:37

0 Answers0