Search code examples
javascriptevent-listenertic-tac-toe

TypeError: Cannot read property 'target' of undefined, error received for checking if a div has not already been filled


Trying to make TicTacToe for an assignment, I'm pretty new to JavaScript, any help would be appreciated:

//onlick event listner
document.getElementById('board').addEventListener('click', handleTurn);

function addMarker(e){
    if(e.target.textContent == fill.EMPTY){ //error shows up for this line specifically
        count++;
        if (count == 1 || count == 3 || count == 5 || count == 7 || count == 9){
            playerTurn = fill.X;
            document.getElementById("switch").innerHTML = "It's O's turn";  
        }   
        else {
            playerTurn = fill.O;
            document.getElementById("switch").innerHTML = "It's X turn";
            
        }
            e.target.textContent = playerTurn;
    }
    else{
        alert('cannot click here, choose a free square!');
    }
    e.stopPropagation();
    handleTurn();
    render();

}

Solution

  • Check for the existence of target.

     if(e.target && e.target.textContent == fill.EMPTY)
    

    And return if no parameter given, when no event or such.

    function addMarker(e){
        if(!e) return;
        if ...