Clay
Clay

Reputation: 13

Run jQuery click function ONCE

I'm having trouble getting this click function to run one single time per turnRound() call. So I put it in an if-statement that should get broken after one execution, due to the humanMoved variable being true. But clicking on an element with the "square" class still calls the click function. turnRound() is called only once as well. I'm thinking this might be a variable scope problem with humanMoved, or I just don't understand .click()

function turnRound(c){
    humanMoved = false;
    if (c == "X" && humanMoved == false) {
        $(".square").click(function(){
            $(this).text(c);
            humanMoved = true;
        });
    }

Upvotes: 0

Views: 73

Answers (1)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167172

Instead of the following code:

$(".square").click(function(){
  $(this).text(c);
  humanMoved = true;
});

Replace it with either .one():

$(".square").one("click", function(){
  $(this).text(c);
  humanMoved = true;
});

Or, you can remove the click event by using .off():

$(".square").click(function(){
  $(this).text(c);
  humanMoved = true;
  $(this).off("click");
});

Upvotes: 2

Related Questions