How can I keep a running total of my die rolls in javascript? -
okay, i've searched everywhere , couldn't find this. have 6 different images of single die. each time user clicks button, image changes. need keep running total, though, , i'm stuck.
<html> <head> </head> <body> <script> function displaydie() { var total=0; var num= ("src",(math.floor(math.random()*6)+1) + ".jpg") document.getelementbyid("die").setattribute("src",(math.floor(math.random()*6)+1) + ".jpg") } </script> <img id="die" alt="die"/> <br/> <input type="button" value="click me!" onclick="displaydie()"/> <span id="total"/></span> </body> </html>
if need know each roll, use array.
var rolls = []; //when rolled, do: rolls.push(<roll value>);
if need total, add integer?
var total = 0; //when rolled, do: total += <value>;
hard give suggestion without more detail on you're after.
edit: ok... sounds project/assignment, i'll try steer in right direction.
if need worry total, there's no need array.
you have total variable declared, that's good.
in displaydie
function, recommend first declare variable , assign random (1-6) number it. add number total, use set source of image.
to display running total, you'll want "total" span using it's id, set value (probably via innertext property) - remove document.write call have.
sounds need add "reset" button set total 0 well.
the for ...
loop not timed function - it's going execute fast possibly can. make sure that's want, or if want settimeout
or setinterval
instead. if loop is want, consider not changing image source during that, it's not going able update fast enough seen anyway.
Comments
Post a Comment