Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reset function on game not working

Tags:

jquery

reset

I've been making a simple tile match game using Jquery and everything is okay except after the game is completed it doesn't reset correctly after clicking the modal box) and you can no longer click the divs to play again.

To see the game and code please go to http://codepen.io/acnorrisuk/pen/JdoGvP/ I have console.logged the array of values so you can cheat 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>");
    }
};
like image 361
Adam Norris Avatar asked Sep 12 '26 23:09

Adam Norris


1 Answers

You are removing all the tile elements (the ones with the "tile" class) when you create a new board. Those tile elements had the click-handler bound to them, but the newly added tile elements do not have a click handler bound to them.

You could move the code that binds the click-handler so it is inside the newBoard() function (after the tile elements are added to the board), but a better way is to use event delegation. With event delegation you can bind the click handler to the #board element, which does not get removed and re-added. But the handler will still get called for the tile elements.

Just change this:

$(".tile").on("click", function () {

To this;

$("#board").on("click", '.tile', function () {

jsfiddle

Note: In the jsfiddle I commented-out the call to shuffle the tiles so it is easier to complete the game.

like image 107
John S Avatar answered Sep 15 '26 13:09

John S



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!