Reputation: 67
I got this problem since 3 days, so the problem is when I move a piece it will refresh the board so that the ai may move, after the refresh in the board the click function stop working.
function drawBoard(board) {
var str = '';
for( var x = 0 ; x < 8 ; x++ ){
for( var y = 0 ; y < 9 ; y++ ){
str += '<div id="mydiv" class="cell" data-square="'+ x +","+ y +'">' +
'<div class="'+checkPiece(board[x][y]) +' '+ getPieceName(board[x][y]) + '" data-value="' + board[x][y] + '"></div>' +
'</div>';
}
}
$('#board').html(str);
}
After I call again the drawBoard(board); to redraw the board the click function stop working.
Upvotes: 0
Views: 62
Reputation: 83356
The problem is in how you're setting up the event handling:
$('.blue').each(function (index, div) {
$(div).click(function() {
will only wire up divs with the blue
class that exist right at that moment. Any divs dynamically added at a later time will not be wired to that event.
You need to use delegated event handling. The simplest, most naive, least performant solution would be to do
$(document).on('click', 'div.blue', function(){ ...
Just note that
$(document).on('click',
is a bit notorious, since since it causes all click events anywhere on the page to bubble up and be checked. If your dom is set up such that all of these divs will always be in their own container, you can and should set up the event handling from there. For example, if all of these divs are in a container called 'foo', you would set up your handler like this:
$('#foo').on('click', 'div.blue', function(){ ....
Upvotes: 2
Reputation: 302
The $.click function only works on objects that exist when it was first called.
Since you're binding it to divs and then wiping them away with an .html() call, the new divs don't have a click event bound to them.
Use $.on instead, and bind it to the larger board object.
$("#board").on("click", "div", function () {
//your click code here
});
That will ensure click events are bound to any future divs placed within the board.
Upvotes: 0