Sams Teach Yourself JavaScript in 24 Hours

Sams Teach Yourself JavaScript in 24 Hours

By Michael Moncur

Workshop: Creating Dynamic HTML Animation

One of the most common uses for positioning is to create animation. In Hour 13, "Using Graphics and Animation," you used JavaScript to create a simple animation. Using the DOM's positioning properties, you can animate the mouse from Hour 13 using a simpler approach.

Just to make things more fun (and because mice are still the only thing I can draw), you will animate three mice at a time using dynamic HTML. Using this technique for the animation provides smoother animation and is easier to program. Listing 19.2 shows the dynamic HTML animation script.

Example 19.2. The dynamic HTML animation script

<html>
<head>
<title>Animation with Dynamic HTML</title>
<script LANGUAGE="JavaScript" type="text/javascript">
var pos1=-95;
var pos2=-95;
var pos3=-95;
var speed1 = Math.floor(Math.random()*10)+2;
var speed2 = Math.floor(Math.random()*10)+2;
var speed3 = Math.floor(Math.random()*10)+2;
function next() {
   pos1 += speed1;
   pos2 += speed2;
   pos3 += speed3;
   if (pos1 > 795) pos1 = -95;
   if (pos2 > 795) pos2 = -95;
   if (pos3 > 795) pos3 = -95;
   document.getElementById("mouse1").style.left = pos1;
   document.getElementById("mouse2").style.left = pos2;
   document.getElementById("mouse3").style.left = pos3;
   window.setTimeout("next()",10);
}
</script>
</head>
<body onLoad="next()">
<h1>Animation with Dynamic HTML</h1>
<hr>
<div ID="mouse1" STYLE="position:absolute; left:0; top:100;
width:100; height:100; visibility:show">
<img src="mouse5.gif" width=100 height=100 alt="" border="0">
</div>
<div ID="mouse2" STYLE="position:absolute; left:0; top:200;
width:100; height:100; visibility:show">
<img src="mouse5.gif" width=100 height=100 alt="" border="0">
</div>
<div ID="mouse3" STYLE="position:absolute; left:0; top:300;
width:100; height:100; visibility:show">
<img src="mouse5.gif" width=100 height=100 alt="" border="0">
</div>
</body>
</html>

As usual, to test this script, load the HTML document into a browser. Remember, since this example uses the new DOM features, it requires Internet Explorer 5.0 or later or Netscape 6.0 or later. Netscape 6's display of the example is shown in Figure 19.2.

19fig02.jpg

Figure 19.2 Netscape 6 displays the animation example.

Share ThisShare This

Informit Network