Monday, September 2, 2019

Update a global variable after button is clicked javascript

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;
}

0

0






No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...