sidosedai323 sidosedai323 - 1 month ago 5
HTML Question

Why does my Button with a script not work sometimes?

I've made a simple script using Javascript which generates a random number between 0-5+1 (Dice.) My issue is that when I press the button, it does nothing half the time forcing me to spam the button multiple times before a dice roll would appear.

I've looked everywhere, but couldn't find any resources as to what the issue might be.
Here is my code:

<html>
<head>
</head>
<body>
<button type="button" onclick="spin()">Click here to roll the Dice!</button>
<img src="" id="demo">
<script>
function spin() {
if (Dice() == 1) {
document.getElementById("demo").src="http://i.imgur.com/QRTs9Ax.png";
}
else if (Dice() == 2) {
document.getElementById("demo").src="http://i.imgur.com/OMz1o8U.png";
}
else if (Dice() == 3) {
document.getElementById("demo").src="http://i.imgur.com/J4Xx2yO.png";
}
else if (Dice() == 4) {
document.getElementById("demo").src="http://i.imgur.com/CJb2ojk.png";
}
else if (Dice() == 5) {
document.getElementById("demo").src="http://i.imgur.com/8W6UL5O.png";
}
else if (Dice() == 6) {
document.getElementById("demo").src="http://i.imgur.com/NGxBete.png";
}
}

</script>
<script>
function Dice() {
return Math.floor(Math.random() * 6) + 1;
}
</script>
</body>
</html>

Answer

Store the value of dice() once to a variable and check it with the if statements. You are regenerating the the value each time so there is no guarantee you will get the current value when checking.

Also, as mentioned by paolo, Math.floor(Math.random() * 6) + 1; could return 7.

<html>
<head>
</head>
<body>
<button type="button" onclick="spin()">Click here to roll the Dice!</button>
<img src="" id="demo">
<script>
function spin() {
    var dice = Dice();
        if (dice == 1) {
            document.getElementById("demo").src="http://i.imgur.com/QRTs9Ax.png";
        }
        else if (dice == 2) {
            document.getElementById("demo").src="http://i.imgur.com/OMz1o8U.png";
        }
        else if (dice == 3) {
            document.getElementById("demo").src="http://i.imgur.com/J4Xx2yO.png";
        }
        else if (dice == 4) {
            document.getElementById("demo").src="http://i.imgur.com/CJb2ojk.png";
        }
        else if (dice == 5) {
            document.getElementById("demo").src="http://i.imgur.com/8W6UL5O.png";
        }
        else if (dice == 6) {
            document.getElementById("demo").src="http://i.imgur.com/NGxBete.png";
        }
}

</script>
<script>
function Dice() {
    return Math.floor(Math.random() * 6) + 1;
}
</script>
</body>
</html>
Comments