JavaScript Tutorial JavaScript Examples CSS Tutorial HTML Tutorial About Us

Animated Digital Dice


We can create an animated digital dice easily using the setInterval() method to be used as the timer. Here we create a JavaScript function rolldice()to generate random integers. The floor method and the random method is to generate random integers from 1 to 6 using the following syntax:

Math.floor( 1 + Math.random() * 6 )

Besides that, we create a JavaScript function AniDice to set the interval of rolldice() to 20 milliseconds.

We use the <div> element to define the size of the digital dice. The id="dice' is to replace the default number 1 with the random numbers.

The HTML is as follows:

<div style="border:4px solid blue; width:100px; height:100px text-align:center;padding:0">
<h1 id="dice" style="font-size:300%">1</h1></div>
<br>
<button onclick="AniDice()">Roll Dice</button>
<button onclick="stopDice()">Stop</button>

<script>

The JavaScript is as follows:

function AniDice()
{
MyVar=setInterval(rolldice,20)
}

function rolldice()
{
var ranNum = Math.floor( 1 + Math.random() * 6 );
document.getElementById("dice").innerHTML = ranNum;

}
function stopDice()
{clearInterval(MyVar);}
</script>

Click on the 'Roll Dice' button to roll the dice

1





Copyright©2008 Dr.Liew Voon Kiong. All rights reserved |Contact|Privacy Policy