JavaScript Tutorial JavaScript Examples jQuery Tutorial CSS Tutorial HTML Tutorial About Us

Lesson 21 Creating Animation


We can create a digital dice by combining jQuery and JavaScript. We use the setInterval() method to start the animation and the clearInterval() method to stop the animation.

Example 21.1 Digital Dice

<!DOCTYPE html>
<html>
<head>
<script>
    $("#roll").click(function(){
       var MyVar=setInterval(rolldice,20)
       $("#timer").text(MyVar);
              function rolldice()
{
    var ranNum = Math.floor( 1 + Math.random() * 6 );
    $("#dice").text(ranNum);
}
    });
    
       $("#stop").click(function(){
       
       var vartime=$("#timer").text()
     
       clearInterval(vartime);
       });
     });
</script>
</head>
<body>
<p><span id="timer" style="display:none"></span></p>

<div style="border:4px solid blue; width:100px; height:100px; text-align:center;padding-bottom:5px">
<h1 id="dice" style="font-size:300%">1</h1>
</div>
<br>
<button id="roll">Roll Dice</button>
<button id="stop">Stop Dice</button>
</body>
</html>

1



Example 21.2 Graphical Dice

This example shows how to create an animated graphical dice.

<!DOCTYPE html>
<html>
<head>
<script>
$(document).ready(function(){
   $("#roll2").click(function(){
       var MVar=setInterval(rolldice2,20);
	    $("#time").text(MVar);
              function rolldice2()
{
var ranN = Math.floor( 1 + Math.random() * 6 );
var dice = document.getElementById("die");
dice.src=ranN+".jpg";

}
});


    
       $("#stop2").click(function(){
       
       var vartmr=$("#time").text()
     
       clearInterval(vartmr);
       });
});
</script>
</head>
<body>
</html>







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