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.
<!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>
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