Search code examples
javascriptdom-eventsjavascript-objects

Add addeventlistener to a nodelist


I am trying to add a click eventListener to some div HTML elements with same class, but I cannot click on my cells when the game is initialized. I am quite new in JS. Any suggestion or hint to point me in the right direction? T

const cells = document.querySelectorAll(".cell");
let gameMark = function(cell) {
  if (gameActive == true) {
    let player = playerTurn();
    let position = parseInt(cell.id[cell.id.length - 1]);
    cell.innerText = player.symb;
    boardArray.array[position] = player.symb;
    gameWin();
    gameTie();
  }
};

cells.forEach(cell => cell.addEventListener('click', gameMark(cell)));
<strike>
<section id="board">
        <div id="gameContainer">
            <div id="row1">
                <div id="cell_0" class="cell"></div>
                <div id="cell_1" class="cell"></div>
                <div id="cell_2" class="cell"></div>
            </div>
            <div id="row2">
                <div id="cell_3" class="cell"></div>
                <div id="cell_4" class="cell"></div>
                <div id="cell_5" class="cell"></div>
            </div>
            <div id="row3">
                <div id="cell_6" class="cell"></div>
                <div id="cell_7" class="cell"></div>
                <div id="cell_8" class="cell"></div>
            </div>
        </div>
      </section>
</strike>


Solution

  • addEventListener expects a function as it's second parameter. You're passing the result of function call.

                                    // calling the function--+ 
                                    //                       |
    cells.forEach(cell => cell.addEventListener('click', gameMark(cell)));
    

    You would need to either change gameMark to return a function:

    let gameMark = function(cell) {
        return function () {
            if (gameActive == true) {
                let player = playerTurn();
                let position = parseInt(cell.id[cell.id.length - 1]);
                cell.innerText = player.symb;
                boardArray.array[position] = player.symb;
                gameWin();
                gameTie();
            }
        }
    };
    

    or use anonymous function in the loop:

    cells.forEach(cell => cell.addEventListener('click', function () {
      gameMark(cell);
    });