How to Create a JavaScript Animation

By Lisha Sterling


Desktop-as-a-Service Designed for Any Cloud ? Nutanix Frame

Making Things Move

Now that you know how to programatically flip the page or change the frame, we need to put something into the frames and move it around. We're going to play with a little ball. Click here to make our example ball visible at the top of the page


First things first. Let's make our ball roll across the screen. OK, so it's not going to roll. It will glide instead, but you get the idea. We're going to make the ball move 5 pixels to the right every 80 milliseconds. Here's the function that will do the moving:

1 function goRight() { 
2     document.images['ball1'].style.left = parseInt(document.images['ball1'].style.left)+5 +"px"
And we'll set our interval in the href:
1 <a href="javascript:var t=setInterval('goRight()', 80)">Try it</a>. <a href="javascript:clearInterval(t)">Stop it</a> 
. Bring the Ball Here so we can see it... Try it;. Stop it

Let's take a moment to look at the code. What have we done here? The object to the left of the equal sign is the location of the image 'ball1'. The expression on the right side of the the equal sign says where that location should be. It needs to be the current location of 'ball1' plus 5 pixels.

But what's with the parseInt() around document.images['ball1'].style.left? The actual content of the variable document.images['ball1'].style.left is an object not a number, so we need to extract the number out of the object in order to perform a mathematical function on it. parseInt(), as I'm sure you've guessed by now, parses the integer out of a variable.

There's one more gotcha you should know about before we move on. In order to use the style position addresses to move an object around the window, you need to give the item an explicit style to start with. You can either declare that style in a CSS style sheet, in the HTML itself, or to declare starting style coordinates in your JavaScript. This last option makes the most sense if the object being moved is created by the JavaScript rather than in your HTML. If you put an object like an image in your HTML and then set "initial" style coordinates in your JavaScript separately, your object could unexpectedly move before the animation begins.

Now that you know how to make your ball move right, it should be pretty easy to make it go left, as well. Use the previous link to move the ball somewhere to the right of your browser window, stop the animation, and try this one.

1 function goLeft() { 
2  document.images['ball1'].style.left = (parseInt(document.images['ball1'].style.left)-5) +"px"
5 <a href="javascript:var t=setInterval('goLeft()', 80)">Go Left</a>. <a href="javascript:clearInterval(t)">Stop</a> 
. Bring the Ball Here... Go Left. Stop

Going up and down is pretty much the same thing. The difference is that we're defining style.top instead of style.left.

Defining The Area Of Motion

Now we know how to move an image to the left or to the right. But what if we don't want to tell it when to stop? What if we want to to go to the edge of the screen and just stop? Well, for that, we need to know where the edge of the screen is. Fortunately, there are ways of finding out. The bad news is not all browsers use the same methods to tell us what we need to know.

Here's our function to find the height and width of our browser window:

1 function computeWin(){ 
2     if(document.body.clientWidth) { 
3         this.windWidth=document.body.clientWidth; 
4         this.windHeight=document.body.clientHeight; 
5     } else { 
6         this.windWidth = window.innerWidth; 
7         this.windHeight=document.innerheight; 
8     } 
9 return this

Notice that we don't bother asking what kind of a browser the user has. That's just a good way to write code that becomes obsolete as soon as you post it to your site. Instead, we ask whether the browser understands what we need. If it doesn't understand the first time, we assume it uses the second method to give us the answer. We could make the code even more portable and add a final static fall back property in case the browser didn't use either of the methods we tried. For our purposes today, that's overkill.

This function gives us an object that we can use easily when we need it. We simply ask for the height or width property of the function and we'll get the property we need. Here it is in action:

1 function animBall() {  
2     imgLeftInt = parseInt(document.images['ball1'].style.left); 
3     imgWidth =  parseInt(document.images['ball1'].width); 
4     winWidth = parseInt(computeWin().windWidth); 
6     if (imgLeftInt <  (winWidth-imgWidth)){ 
7         goRight(); 
8     } else { 
9         clearInterval(t); 
10     } 
13 <a href="javascript:setInterval('animBall()',80)">Try It</a> 
Bring the Ball Here... Try It

A Little Random Action

Let's make this a little more interesting. I want my ball to move at different speeds. And not only that, I want it to switch directions when it gets to the edge of the screen. Can we do that? Of course we can.

Let's start with the random number generator:

1 function setRand() { 
2     randnum= Math.floor(Math.random()*6)+2; 
3     return randnum; 

This function sets a random number between 2 and 7. Math.floor() rounds down to the nearest integer. Math.random() gives you a random number between 0 and 1, exclusively. Not 0 and not 1, but something in between. That means, after multiplying times 6 and rounding it down, we'll get a number between 0 and 5. We're adding 2 to the result because 0 pixels equals no movement equals one seriously boring animation.

Now, let's change the direction. We'll do that by creating a variable that holds our direction information. We'll call it diry since we're moving around on the y axis (up and down). Before we start any function stuff, we'll just declare diry to be 1, and in our heads we'll call that down. While we're at it, let's declare our speed, too, and set it using setRand().

1 var diry = 1; 
2 var spdy = setRand(); 

Having done that, we can create our up and down direction functions so they take the new speed and direction variables. We'll want to use the same speed and direction for one entire journey from one edge of the window to the other, but when we switch directions, we need to change both variables before the next time our animation function runs. Here's how we do it:

1 function goDown() { 
2     document.images['ball1'].style.top = imgTopInt+spdy+"px"
3     if (imgTopInt >  (winHeight-imgHeight)){       // we've hit the edge of the screen 
4         diry = 0;                                              // next time through go up 
5         spdy= setRand();                                 // set my new speed 
6     } 
10 function goUp() { 
11     document.images['ball1'].style.top = (imgTopInt-spdy) +"px"
12     if (imgTopInt < 5){                                        // we've hit the top of the screen 
13         diry = 1;                                               // next time through go down 
14         spdy= setRand();                                  // set my new speed 
15     } 

We're going to call the goUp() and goDown() functions from inside animBall(). That way we can set our interval, and let the computer do the rest. The ball will bounce up and down to its heart's content, and we can just clear the interval when we've had enough. Here's the new animBall() code:

1 function animBall() {           
2     imgTopInt = parseInt(document.images['ball1'].style.top); 
3     imgHeight =  parseInt(document.images['ball1'].height); 
4     winHeight = parseInt(computeWin().windHeight); 
6     if(diry == 1) {                         // if I'm supposed to go down... 
7         goDown();                    
8     } else {                                   // if not, I guess I'd better go up! 
9         goUp(); 
10     } 

Page 2 of 3

Previous Page
1 2 3
Next Page

  • Web Development Newsletter Signup

    Invalid email
    You have successfuly registered to our newsletter.
Thanks for your registration, follow us on our social networks to keep up-to-date