I've declared the variable elem in both of the loops below; however, when the anonymous function in the first loop gets called (after the 400ms fadeOut effect is finished) the elem seems to refer to the value of elem which was assigned in the second loop. In other words, the code works correctly if you rename elem in the second loop to any other variable name.
Is there a way to make a closure around the anonymous function so that the value of elem is not changed in the context of the anonymous function?
for (var i = 0; i < outs.length; i++) {
var elem = this.elementAtPoint(outs[i]);
$(elem).fadeOut(400, function () {
$(elem).removeClass("white black queen"); //UPDATE
$(elem).show();
});
//$(elem).css("background", "red");
}
for (var i = 0; i < ins.length; i++) {
var elem = this.elementAtPoint(ins[i]);
var piece = this.board.pieceAt(ins[i]);
$(elem).hide();
$(elem).addClass(this.classForPiece(piece));
$(elem).fadeIn(400);
}
out? You can loop arrays and objects with jQuery's$.eachwhich creates a new scope.JavaScript Hoisting