Проблема в том, что найденная переменная присваивается в момент щелчка.В этот момент вы уже связали оба прослушивателя событий с элементами, и они будут оставаться там до тех пор, пока не будут удалены.Если вы хотите, чтобы когда-либо происходило только одно, вам нужно сделать оператор if внутри клика.
let found = false
function myFunction(){
($('#character').click(function(){
if (found === false){
$('#redBox').animate({right: '-=700px'});
$("#redBox").css({backgroundColor: "grey"});
$('#blueBox').animate({right: '-=700px'});
$("#blueBox").css({backgroundColor: "grey"});
found = true;
}
}));
}
myFunction();
($('#redBox').click(function(){
if (found === false){
$('#character').animate({right: '-=700px'});
$("#character").css({backgroundColor: "grey"});
$('#blueBox').animate({right: '-=700px'});
$("#blueBox").css({backgroundColor: "grey"});
found = true;
};
}));
но, если я могу предположить, лучше / чище структура для этого может быть:
var fired = false;
$('#redBox, #character').click(function(e){
if(! fired){
fired = true;
if(this.id === "redBox"){
$('#character').animate({right: '-=700px'});
$("#character").css({backgroundColor: "grey"});
}else{
$('#redBox').animate({right: '-=700px'});
$("#redBox").css({backgroundColor: "grey"});
}
$('#blueBox').animate({right: '-=700px'});
$("#blueBox").css({backgroundColor: "grey"});
}
});
Кроме того, вы можете избавиться от оператора if все вместе, и простоудалить прослушиватель событий после первого вызова.Это оказывает положительное влияние на страницу, потому что вы больше не вызываете эту функцию для будущих кликов.Минимальный в этом случае, но хорошая практика все же:
$('#redBox, #character').on('click', function(e){
if(this.id === "redBox"){
$('#character').animate({right: '-=700px'});
$("#character").css({backgroundColor: "grey"});
}else{
$('#redBox').animate({right: '-=700px'});
$("#redBox").css({backgroundColor: "grey"});
}
$('#blueBox').animate({right: '-=700px'});
$("#blueBox").css({backgroundColor: "grey"});
$('#redBox, #character').off('click');//remove the event from #redBox and #character
});