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.
source share