Search code examples
javascriptjqueryhtmlcss2d-games

JS/JQ Whack-A-Mole Game


Hello guys Im trying to make a JS/JQ game : Whack A Mole.

I have made a 'world' where there are 6 div's that can change color ( to show where the mole is) , I also have three buttons to choose easy , normal or hard.

I'm stuck on two things : 1 : the button.click does not react to anything ( not even the simpelest css change on a p ) 2 : the divs don't change color ( this might be a follow-up for problem 1)

Here is my code :

the p with ID "car" and text "blablacar" is to show the 'simple' click command to change color.

Can anyone see whats wrong ( probably a lot , but just for the button part ) with my code? Thank you for reading my post

enter code here



<body>

    <script type="text/javascript" src="../jquery-3.1.1.js">
    "use strict";

        var currentScore = 0;
        var niveau = 0;
        var currentLives = 3;
        var inAction = false;

        var moleworld = "#moleWorld";
        var field = ".field";

        var beginEasyClick = document.getElementById("beginEasyClick");
        var beginnNormalClick = document.getElementById("beginNormalClick");
        var beginHardClick = document.getElementById("beginHardClick");

        var displayScore = document.getElementById("_displayScore");
        var $field = $(moleworld).find(field);


        var getrandomInt(function(min , max)
                         {return Math.floor(Math.random() * (max - min - 1 )) + min}

        function randomField() {
$($field[getrandomInt(0 , 8)]);





            function showmole()
            {
                $(beginEasyClick).click(function{

                $("#car").css("color" , "blue");
            })};

    </script>
<p id="car">blablacar</p>
<div id="StartMenu"></div>
 <button id="beginEasyClick"> Easy </button>
    <button id="beginNormalClick"> Normal </button>
    <button id="beginHardClick"> Hard </button>
<div id="generalInformation">
<p id="_displayScore"> </p> </div>

<div id="moleWorld">

  <div class="field"> </div> 
     <div class="field"> </div> 
     <div class="field"> </div> 
     <div class="field"> </div> 
     <div class="field"> </div> 
     <div class="field"> </div> 
    <div class="field"> </div> 
    <div class="field"> </div> 
    </div>

</body>


Solution

  • Besides some bracketing errors (even parameterless functions need to have empty () brackets), the click() event handler for the button is defined inside the showmole() function which is not called anywhere. You have to move this part into the $().ready() part of your script so that the handler is added as soon as the document has been loaded.

    $().ready(function() {
      $(beginEasyClick).click(function () {
        $("#car").css("color", "blue");
      });
    });
    

    As mentioned in the comments you should also in the future post your code on jsfiddle so that others can more easily help you. Here's the fiddle for your code with a working "easy" button.