vendredi 19 août 2016

Update a global variable after button is clicked javascript [duplicate]

This question already has an answer here:

I tried understanding the solutions to this on past threads but couldn't find exactly what I was looking for.

I have 2 dice that roll when a button is clicked. I want to be able to create a running total of the numbers that result from each roll.

Example: 
Roll 1 is 3+4 = 7 | Running total = 7
Roll 2 is 2+6 = 8 | Running total = 15
Roll 3 is 4+1 = 5 | Running total = 20

Here is my code. I have a global variable being updated but I get NaN for var running3.

Any help is greatly appreciated while I learn JS. Thank you.

var running2 = null;

function rollDice() {
  var die1 = document.getElementById("die1");
  var die2 = document.getElementById("die2");
  var status = document.getElementById("status");
  var status2 = document.getElementById("status2");
  var d1 = Math.floor(Math.random() * 6) + 1;
  var d2 = Math.floor(Math.random() * 6) + 1;
  var diceTotal = d1 + d2;

  die1.innerHTML = d1;
  die2.innerHTML = d2;

  var running3 = (diceTotal + running2);
  var running2 = running3;
  status.innerHTML = "You rolled " + diceTotal;
  // if(d1 == d2){
  //     status.innerHTML += " DOUBLES! You get a free turn!!";
  // }

  status2.innerHTML = "Your running " + running3;

}
div.dice {
  float: left;
  width: 32px;
  background: #F5F5F5;
  border: #999 1px solid;
  padding: 10px;
  font-size: 24px;
  text-align: center;
  margin: 5px;
}
<div id="die1" class="dice">0</div>
<div id="die2" class="dice">0</div>
<button onclick="rollDice()">Roll Dice</button>
<h2 id="status" style="clear:both;"></h2>
<h2 id="status2" style="clear:both;"></h2>



Aucun commentaire:

Enregistrer un commentaire