# Lesson 21 Creating Animation

JQuery can perform arithmetic easily using arithmetic operators.

#### Example 21.1 Digital Dice

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>
<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>
<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 20.2 Graphical Dice

This example shows how to create a math drill using random number.

We use parseInt(Math.random()*n) to generate random integers between 0 and n. We also use the if else conditional operators to check the answer input by the user.

```<!DOCTYPE html>
<html>
<script>
\$("#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>
<body>
<h1>Math Drill</h1>
<p>x=<span id="num1"></span></p>
<p>y=<span id="num2"></span></p>
x+y=<input type="text" id="ans_sum"><br>
<button id="btn2">Generate Numbers</button>