ecooper10
ecooper10

Reputation: 107

Jquery .on() not calling selector

I am trying to make the image of the mole clickable and once clicked will increase the score but the .on() will not work with the class name of the image. It will, however, work if I use the selector "#gamespace", but then clicking anywhere within the game space will get the player points rather than just clicking the mole.

<!DOCTYPE html>
<html>
  <head>

    <title>Whack-A-Mole (CSCI2447)</title>

    <!-- CSS styles: This is for me to worry about; not you. -->
    <link href="css/game.css" rel="stylesheet" />
    <script src="js/jquery-2.2.1.min.js"></script>
    <script type="text/javascript">
    var score = 0
    var time = 30
    var t;
    var moleRepeat;
    $(document).ready(function(){
    $('#start_button').click(function (){
    start();
    });
    $('.mole').on('click' , function () {
    counter();
    });
    });

    function getYRandomNumber(){
        return Math.floor((Math.random()*300)+0);
      };

    function getXRandomNumber(){
        return Math.floor((Math.random()*600)+0);
      };

     function counter() {
     score++;
     $("#score").html(score + ' pts');
     };

     function start() {
     $('#timer').show();
     addMole();
     decrement();
     $('h1').css("color","purple");
     $('#gamespace').css("background-color", "green");
     };

     function decrement() {
     time--;
     $('#timer').html(time + ' seconds left');
     t = setTimeout('decrement()', 1000);
     };

     function addMole() {
     $('#gamespace').append('<img class="mole" src="img/mole.png" onClick="counter()"/>');
     moleRepeat = setTimeout('addMole()', 2000);
     };
    </script>
  </head>
  <body>

    <div id="content">

        <h1>Whack-A-Mole</h1>

        <p>After clicking "start", you will have 30 seconds to click
        as many moles as you can. The moles appear randomly so be ready! </p>

        <div id="controls">
            <span id="score">0 pts</span>
            <button type="button" id="start_button">Start!</button>
        </div>

        <div id="timer">30 seconds left</div>

        <div id="gamespace">



        </div>

    </div>
  </body>
</html>

Upvotes: 1

Views: 145

Answers (2)

Taplar
Taplar

Reputation: 24965

It looks like your trying to bind to the click event of '.mole' before any exist. Direct bindings only work for elements that already exist in the DOM. You could fix this by doing a delegate binding.

$('#content').on('click', '.mole', function(){ ... });

This will make it listen for the bubbled events from mole elements. Since it works with the bubbled events, it does not matter when they are created.

Upvotes: 1

The Process
The Process

Reputation: 5953

You are adding click event handler on .mole before it is appended to #gamespace and exist on the page, use event delegation instead

$('#gamespace').on('click','.mole' ,function () {
    counter();
 });

Upvotes: 3

Related Questions