Jlouk Jlouk - 1 year ago 80
Javascript Question

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.

height: 400px;
width: 200px;
border:solid 1px green;
float: left

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!!";
<div class="numdiv" id="number1">

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



Answer Source

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!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download