How to use the SetInterval and "if" function to make a div pop up?

I have this script for the game Whack a mole, but I can’t get my div to pop up when I want using a random number generator. This is my code: (by the way, this is my first game I have ever made, so this was a pretty dumb question :))

//minigame setInterval(function() { var randomnumber = 1 + Math.floor(Math.random() * 10); if (randomnumber = "1") { $('#mole1').show(); }; if (randomnumber = '2') { $('#mole1').show(); }; if (randomnumber = '3') { $('#mole1').show().delay(300).hide(); }; if (randomnumber = '4') { $('#mole1').show().delay(300).hide(); }; if (randomnumber = '5') { $('#mole1').show().delay(300).hide(); }; if (randomnumber = '6') { $('#mole1').show().delay(300).hide(); }; }, 200); 

and my html relevant:

  <div id="minigameblockholder"> <div class='moles' id="mole1"> </div> <div class='moles' id="mole2"> </div> <div class='moles' id="mole3"> </div> <div class='moles' id="mole4"> </div> <div class='moles' id="mole5"> </div> <div class='moles' id="mole6"> </div> <div id="scorebord"> </div> </div> 

I have not started working on my scoreboard, but I am not correcting it. thanks at advnce, jasper

+6
source share
1 answer

Edit

I don’t know if you edited your answer, however I see some things that would prevent it from working.

Your if statements will not work. You use the assignment operator ("="), so you assign variables.

var x = 2; (assign 2 to x variable)

You need to use the operator "==" (equal) in comparison.

if(randomnumber == 2) (if the number of random numbers is 2)

Orig. answer

Following my comment, I do not see from your code why it does not work. However, you can try something like the following:

 setInterval(function(){ var randomnumber = 1 + Math.floor(Math.random() * 10); $('#mole1').html(randomnumber); var mole = $('#mole' + randomnumber); if(mole != undefined){ $('.moles').hide(); mole.show(); } }, 2000) 

This creates a random number, attaches it to the id "mole" (for example: mole + 2) and checks if it is defined (exists). If so, he hides all the other moles and shows the selected mole (in our example 2). It will also save you from all if statements and allow you to increase or decrease the number of moles without creating additional checks for them.

You can see that it works here https://jsfiddle.net/ezs00xw0/

Note. Ignore the extra html and css, this was for debugging purposes.

+4
source

All Articles