Clay Clay - 6 months ago 18
Javascript Question

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;
});
}

Answer

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");
});