0

fairly new to HTML/Javscript here. I have an HTML page with squares in it, and I am trying to get each square to move a certain way when the user clicks on it. I have an array called board that stores the names of the squares and I am trying to add an event listener to all but one square called "red." Calling getMove() on an element causes it to move in a direction determined by the placement of other squares.

addListeners() is being called, but the event listeners are not working. Any suggestions?

function addListeners()
{
  for(var i = 0; i < dim; i++)
  {
    for(var j = 0; j < dim; j++)
    {
      if(board[i][j] != "red")
      {
        console.log(board[i][j]);
        var elem = document.getElementById(board[i][j]);
        elem.addEventListener("click", function(){getMove(elem);});
      }
    }
  }
}

document.addEventListener("DOMContentLoaded", addListeners);
MLE
  • 69
  • 6
  • what is `board`? what is `getMove`? what is your html structure? Please provide a complete example (even if not everything is working). – Dekel Dec 03 '16 at 00:41
  • My suggestion is Google: [site:stackoverflow.com javascript Adding event listeners in a loop](https://www.google.com/search?q=site%3Astackoverflow.com+javascript+Adding+event+listeners+in+a+loop) That said, you can change your call to `getMove(this)` to pass the clicked element. –  Dec 03 '16 at 00:41
  • Please include more context, for example what is `dim` and `board` ?. – rckrd Dec 03 '16 at 00:42
  • Maybe the answer on this question helps you: [addEventListener using for loop and passing values](http://stackoverflow.com/questions/19586137/addeventlistener-using-for-loop-and-passing-values ) – Wesley Dec 03 '16 at 00:44

0 Answers0