Reset function does not work
I am making a simple tiling game using JQuery and it is ok if after the game is finished it is not reset correctly after clicking the modal) and you can no longer click the divs to play again.
To see the game and the code, go to http://codepen.io/acnorrisuk/pen/JdoGvP/ I have a console.logged array of values so you can trick your way through the game to see what happens when it resets.
The reset function is below:
function newBoard() {
// reset variables
tiles_flipped = 0;
temp_values.length = 0;
tile_values.shuffle();
tile1 = '';
tile2 = '';
$("#board").empty();
$(".tile").removeClass("transform");
$("#score").html("<p>Pairs Found: " + 0 + "</p>");
// gives each div a unique tile number and inserts images
for (var i = 0; i < tile_values.length; i++) {
$("#board").append("<div class='flip-container flip'>\
<div class='tile flipper' id='" + i + "'>\
<div class='front'></div>\
<div class='back'><img src='" +
tile_values[i] + "'>\
</div>\
</div>\
</div>");
}
};
source to share
You remove all tile items (those with a tile class) when you create a new board. These tile items had a clicker attached to them, but newly added tile items do not have a snap to them.
You can port the code that binds the click handler to be inside the function newBoard()
(after adding tile elements to the board), but the best way is to use event delegation. When delegating events, you can bind a click handler to an element #board
that is not removed or re-added. But the handler will still be called for tile elements.
Just change this:
$(".tile").on("click", function () {
For this
$("#board").on("click", '.tile', function () {
Note. In the jsfiddle, I commented out the call to shuffle the fragments to make it easier to complete the game.
source to share
Since you are adding .tile
in #board
to your function newBoard
, you need to delegate the click event :
// check if tiles match using a temporary array
$("#board").on("click", '.tile', function () {
...
});
source to share
I managed to get it working, see http://codepen.io/anon/pen/bdNpGK .
The problem was that you were only adding the onClick function to the first set of maps. When you reset on a board, you removed all old cards, added new ones, but never set the on click function. Instead of an anonymous function on the onClick event, it now adds a corresponding click function every time reset is called.
function newBoard() {
...
$(".tile").on("click", onClick);
}
function onClick() {
...
}
source to share