Dhtml Animation Example

Basic Animation A working animation using setTimeout().

Here is the code that moves the graphic across the page.
You should study the javascript function moveit() carefully.

<head>
<title>Basic Animation</title>
<style type='text/css'>
#piccy {position:absolute; top:150px;left:400px;}
</style>
<script type='text/javascript'>
<!--
position=0;
function moveit(){
document.getElementById("piccy").style.left=position+400+'px';
if(position>-300){position=position-2};
setTimeout("moveit()",20);
}
//-->
</script>
</head>
<body>
<h3>A Simple dhtml Animation</h3>
<form action=''>
<input type='button' value='Move it' onclick='moveit();'>
</form>
<div id='piccy'> <img src="rosehead.gif" alt='rosehead' /></div>
</body>

Here is how our javascript function called moveit() works

Exercises

1. Use the code above to create a similar web page with a graphic of your choice

2. Adjust the speed and locations of the animation by changing values in the moveit() function

3. Change the animation so it runs in the opposite direction from left to right.

4. Using the style.top property make the graphic move up or down the screen

5. Make the graphic move from the top left of the screen to the bottom right

Monkey Business An example of vertical movement.