I'm building a chess app as a summer project and it works by submitting jQuery requests when pieces or squares are clicked. When a piece is clicked the request will return the valid squares for that piece to move to and then it adds a dot on that square to indicate that it can be moved there (it removes the dot after a square or other piece is clicked). The problem is that if there is already a piece on that square, the dot is added and then when it is removed, when the piece is clicked it no longer fires the Javascript. When I refresh the page it works fine again. How can I fix this so that even when a dot is added and then removed, clicking the piece will fire the js correctly?
This is the js code that runs when a piece is clicked:
$("img.piece").on("click", function(){
if (parent != undefined && parent.attr("class")=="light_square"){
parent.css("background-color","WhiteSmoke");
$(".dot").remove();
} else if (parent != undefined && parent.attr("class")=="dark_square") {
parent.css("background-color","Sienna");
$(".dot").remove();
}
parent = $(this).parent();
sq_one = $(this).attr("id").slice(5,10);
parent.css("background-color", "Gold");
$.ajax({
contentType: 'application/json;charset=UTF-8',
type:'POST',
url:"/moves",
data:JSON.stringify({'sq_one':sq_one}),
success: function(response) {
for (x in response) {
var id = "square("+response[x]+")";
document.getElementById(id).innerHTML += ("<span class=\"dot\"></span>");
}
}
});
});
$(".dot").remove();
is also used when a square is clicked.
The CSS for dots, squares, and pieces is as follows:
.dark_square {
background-color: Sienna;
width: 45px;
height: 45px;
text-align:center;
position: relative;
}
.dot {
height: 20px;
width: 20px;
background-color: #bbb;
border-radius: 50%;
display: inline-block;
opacity: 0.5;
top: 50%;
left: 50%;
position:absolute;
transform: translate(-50%, -50%);
}
.piece {
width: 42px;
height: 42px;
}
Finally I'm using a table to do the board and the html looks like this:
<td id="square({{ 8-x }},{{ y+1 }})" class="light_square">
<img id="piece({{ 8-x }},{{ y+1 }})" class="piece" src="/static/images/{{ img_dict[(8-x,y+1)] }}">
</td>