I’m a beginner with only 2 months experience in front-end. I’m trying to make a simple web-grid game.
I’ve got a 10×10 grid table (grid container with 100 div child elements in it), and my goal is that, when the site is opened, a random grid item out of the 100 gets automatically selected, and when the user clicks on that randomly selected grid item, another grid item out of the 100 gets randomly selected automatically, and the previously selected item gets de-selected (color goes back to the default state for example).
I was thinking I could do something with Math.random
, but I don’t know how. Any help or suggestions is appreciated!
HTML code is just
<div class="grid-container"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<!-- ... a hundred of these child elements for 10x10. -->
</div>
JavaScript is blank
3
Answers
after creating 100 grids give them dynamic Id with using (for)
then use below function:
// it returns you a number between 1 to 100 then get the item as bellow:
and other step you want
You will have to technically view each grid as a number to achieve what you stated above. So:
Generate a list of random numbers from 1 – 100. Each number denotes a grid that you can show on the screen.
You will need a state variable to store the selected grid (represented as a number). According to your question, you need a grid to be selected at random on load, so that means you will need to set the state variable to be equal to a random number from 1 – 100 on load. Whatever number is selected as random will denote the randomly selected grid on load.
Whenever you click on a grid (technically a number), you set the state variable to the new grid click (number).
You can then style as you want, you can assign a selected class(CSS) to the grid whose ID is the same as the state variable.
Here is a rough example.
index.html
index.js
style.css
I don’t think you necessarily even need to give each div an id; you could use its index in a
querySelectorAll()