0

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;
        });
    }
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
Clay
  • 13
  • 3

1 Answers1

2

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");
});
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252