Search code examples
javascriptdice

How to roll one dice at a time?


So here is what I have so far. I am very new to javascript. How do I make these dice roll sequentially inside of the divs? Such as only displaying the next random number only after the first one is displayed.

<html>
<style>
.numdiv{
height: 400px;
width: 200px;
border:solid 1px green; 
float: left
}
</style>

<head>
<script>
function rollDice(){
var number1 = document.getElementById("number1");
var number2 = document.getElementById("number2");
var number3 = document.getElementById("number3");
var status = document.getElementById("status");
var d1 = Math.floor(Math.random() * 6) + 1;
var d2 = Math.floor(Math.random() * 6) + 1;
var d3 = Math.floor(Math.random() * 6) + 1;
var diceTotal = d1 + d2 + d3;

    number1.innerHTML = d1;
    number2.innerHTML = d2;
    number3.innerHTML = d3;
    status.innerHTML = "You rolled "+diceTotal+".";
    if(diceTotal == 15){
        status.innerHTML += "You Win!!";
    }
}
</script>
</head>
<body>
<table>
<tr>
<td>
<div class="numdiv" id="number1">

0</div>
<div class="numdiv"  id="number2">
0</div>
<div class="numdiv"  id="number3">
0</div>
</td>
</tr>
<tr>
<td><button onclick="rollDice()"/>Generate Number</button></td></tr>
<tr>
<td><span id="status">0</span></td></tr>
</table>

</body>


</html>

Solution

  • Create a counter variable starting with one outside of your rollDice function and every time that is clicked then increase the counter by one. Then you need to replace all the number variables with just this:

    var number = document.getElementById("number" + counter);
    

    I think you know where to go from here. Let me know if you need more guidance!