Skip to content
Advertisement

How to show random images in random grid child for vanilla JS whack-a-mole

I´m working in a whack-a-mole game in vanilla JS (following this tutorial https://www.youtube.com/watch?v=rJU3tHLgb_c&t=1s) and I would like to display a random image every time the mole appears on the screen instead of the same mole image. Right now what I get is the same random image repeated in each square. This is not what I want and I don´t understand why this is happening. I would appreciate any help!

JavaScript
JavaScript
JavaScript

Advertisement

Answer

You just have to move the definition of selectBG in the function randomSquare(). Otherwise you will always use the same selectBG which you defined as constant at the beginning (where the random function runs only once).

If you only want one background image to be visible you have to reset the backgrounds for all squares at that point where you remove the class .mole from all squares.

JavaScript

Working example:

JavaScript
JavaScript
JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement