1

Recently I started to learn HTML/CSS and jQuery so I was trying to make a little web game. here is the code of HTML:

function playGame() {
        var theLine = "<div id = \"line\">";

        for (var i = 0; i < 9; i++) {
            theLine = theLine + "<button class=\"ticButton\"> chose </button>";
        }

        theLine = theLine + "</div>";
        var instr = "<p id = \"ins\"> choose wisely </p>";

        $("body").append(instr);
        $("body").append(theLine);
    }

    $(document).ready(function () {
        $("#game").click(function () {
            alert("be aware");
            $("#game").hide();
            playGame();
        });

        $(".ticButton").click(function () {
            alert("you won");
        });
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
    <html>
     <head>
 <title> Play </title>
 <script src="jquery-3.1.1.js"></script>
 <script src="behavior.js" type="text/Javascript"></script>
 <link href="style.css" rel = "stylesheet" type="text/CSS" />
     </head>
     <body>
 <h1> Welcome </h1>
 <button id="game"> play </button>
 
    </body>
    </html>

so my purpose is, after clicking the play (id = game) button, there should appear 9 new buttons and after clicking any of them the alert should be raised saying: you won. But what happens is: after 9 new buttons appear, nothing happens when you click them. Any suggestions? I want to mention that there is a question about event listeners, which doesn't work after dynamic creating but that question and its answers was not helpful for me.

GeorgeDopeG
  • 145
  • 12
  • 1
    didn't you mean `$("#game")` instead of `$("game")`? – mic4ael Feb 03 '17 at 15:59
  • @mic4ael "_But what happens is: after 9 new buttons appear..._" So this looks like a simple typo, otherwise `playGame()` wouldn't be executed – Andreas Feb 03 '17 at 16:00
  • Man, this question seems to be all over today. This is [third](http://stackoverflow.com/questions/42026750/jquery-readless-toogle-function/42026876#42026876) or [fourth](http://stackoverflow.com/questions/42025444/jquery-not-selecting-element/42025520#comment71225022_42025520) one in the past hour alone. – Tyler Roper Feb 03 '17 at 16:03

1 Answers1

5
$(".ticButton").click(function() {
    alert("you won");
});

This adds an event listener to all currently existing elements (Elements existing when the page is initially loaded the). Your elements are added after that, that's why nothing happens.

Declare your event with .on() like this

$(document).on("click", ".ticButton", function() {
    alert("you won");
});
VaLLe.
  • 160
  • 1
  • 6