Home Javascript - Updating global variable value
Reply: 0

Javascript - Updating global variable value

Matthew
1#
Matthew Published in 2017-11-12 16:00:44Z

I'm trying to create a simple dice roller (2 dice, 6 sides). Two variables have an initial value of '1'.

A switch statement was created so that different dice images of different sides will show according to the dice variable value.

A function for generating a random number between 1 and 6 was created to simulate throwing 6 sided dice. Another function was created so that the variables will update with a random number generated when a button is clicked.

JS:
var die1 = 1;
var die2 = 1;

function getRandomNumber(){
 return Math.floor(Math.random()*6)+1;
};

function rollDice(){
 die1 = getRandomNumber();
 die2 = getRandomNumber();
};

switch (die1){
case 1:
    document.getElementById("die1").src="imgs/dice-1.png";
    break;
case 2:
    document.getElementById("die1").src="imgs/dice-2.png";
    break;
case 3:
    document.getElementById("die1").src="imgs/dice-3.png";
    break;
case 4:
    document.getElementById("die1").src="imgs/dice-4.png";
    break;
case 5:
    document.getElementById("die1").src="imgs/dice-5.png";
    break;
case 6:
    document.getElementById("die1").src="imgs/dice-6.png";
    break;
};    //duplicated code for 'die2'

HTML:
<button id="roll" onclick="rollDice()">Roll</button>

However, when clicking the roll button, the variables are not updating and consequently, the dice images are not changing.

Can someone suggest a way this can be done? Or if an alternative take on this is required. Thanks.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.253731 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO