ga-dc / wdi5-project4

3 stars 0 forks source link

event listener issue #124

Closed lmdragun closed 9 years ago

lmdragun commented 9 years ago

I have an event listener at the very beginning of my game, on the start button. I wanted to have a restart button after the game is over where the players can just click that instead of refreshing. I'm making it with javascript and for some reason the event listener isn't catching it.

(#start is the 'modal' like popup I have at the beginning and end of the game)

my gameOver function:

    gameOver: function(){
        clearInterval(timerSeconds);
        $("#start").css("display", "block").append("<h1>GAME OVER</h1>");
        $("#start").append("<p>Play again?</p>").append("<button class=\"restart\">Start the Game</button>");
}

my event listener:

    $(".restart").on("click", function(){
        $("#start").empty();
        $("#start").css("display", "none");
        this.model.getDetails(this.showDetails.bind(this));
        this.gameLoop();
    }.bind(this));

I also tried just using the "start" listener over again, which works initially but doesn't work for this new one.

RobertAKARobin commented 9 years ago

Do you get an error? And have you console.log-ed through your script to see where it starts to break?

lmdragun commented 9 years ago

Nope, no errors, nothing javascript-y happening at all when I click. I looked in the chrome console and the class IS appearing when the button appears.

RobertAKARobin commented 9 years ago

Ah, I see now. Event listeners set on page load only work on the elements that were created when the page was loaded. So if you have this:

$(document).ready(function(){
  $(".blah").click(function(){
    console.log("Hello");
  });
});

...it won't work on any new .blah you create. You'll have to re-attach the event listener.

lmdragun commented 9 years ago

How would I re-attach? just have it within the function that creates the new button?

RobertAKARobin commented 9 years ago

Try it!