decoder
decoder

Reputation: 137

Not able to check if Tic-tac-toe a square is empty using jQuery

I'm coding a Tic-tac-toe game but the code which I'm using to check whether the user is clicking on an empty square or an already filled one is not working for me. Please find my mistake.

function startgame(){
    var $board=$('#board');
    $('div.square').remove();

    for(var i=0;i<9;i++)
        $board.append($('<div/>').addClass('square').addClass('empty'));

    $('div.square.empty').click(function(){
        $this=$(this);

        if($('div.square.empty').length==0){

            displayendmsg();
        }
        else {
            $this.removeClass('empty');

            if(currentplayer=="X")
                $this.append($('<div><img src="cross.jpg">        </div>').addClass('cross').css('visibility','visible'));
            else
                $this.append($('<div><img src="circle.jpg">  </div>').addClass('circle').css('visibility','visible'));

            flipturn();
        }


    });
};

Even when clicking on an already occupied square I enter the handler, and I don't know why.

Upvotes: 0

Views: 204

Answers (2)

Eric
Eric

Reputation: 1374

.click() attaches an event handler on call time to all elements that match the selector. Even if the elements don't match the selector later on, the event handler will still be there.

Instead, use .on() to check if the selector still applies for your event handler at the moment it is triggered:

$(document).on("click", "div.square.empty", function(){ alert("Clicked an empty square!"); });

Upvotes: 1

ThiefMaster
ThiefMaster

Reputation: 318488

Your problem is that you bind the event handler only for the elements that match the selector at the time where you call the .click(..) function. However, you want to bind it on all elements but only trigger the function if the element has the correct class.

You can do this by using a delegate. In recent jQuery versions you do this using the .on() method:

$('div.square').on('click', '.empty', function() {
    // your code here
});

Upvotes: 0

Related Questions