Click here to Skip to main content
Click here to Skip to main content

Introduction to Javascript Animation

, 24 Jul 2008
Rate this:
Please Sign up or sign in to vote.
An introduction to animation in Javascript

Contents

Introduction

For the past couple of years, the Internet has been advancing rapidly. The introduction of methods such as AJAX have led the web forward, and coupled with the ever advancing developments in software, technology and users's expectations of the web, the standards of web design are being pushed ever higher.

Web pages are forever becoming more user-friendly and rich, implementing sleek transitions and soft graphics; one element to these feature-rich pages is animation. Many websites feature animation through such transitions as fading or flashing buttons or roll-up and down elements. All these animations can be created fairly easy using Javascript, and this article will provide an introduction to this.

Prerequisites

In order to be able to follow this article and use it, a general understanding of Javascript is required, however as it provides only an introduction to Javascript animation, more complex concepts and methods are not explored in too much detail.

Animating Objects

The Concept

The concept of animating an object in Javascript is the same to that of animating anything. The object that is being animated is changed over a number of "steps" set at a certain interval, over a certain period of time. At each step the object may be changed in any number of ways, and the smooth running of this is what causes the object to appear animated. This animation concept can be implemented relatively easily using Javascript, as explained below.

A Basic Animation

Personally, my favourite animation to write in Javascript is a fade function, simply because as it only changes one property (the object's opacity), it is very easy to implement. Before getting into the code, however, there are two key functions and styles that need to be explained:

setTimeout(code, milliseconds): This function is part of the Javascript library, and calls the specified code after the number of milliseconds has elapsed. It is supported in all browsers as standard.

obj.style.opacity, obj.style.filter: The opacity style was introduced with CSS2. It is supported in IE and Mozilla-based browsers (Firefox, Safari etc) but is implemented differently in both. In IE it is implemented as a filter, with the value being alpha(opacity=o), where o is a number between 0-100, 0 being completely transparent and 100 being completely opaque, and in Mozilla-based browsers as a style, opacity, with a value between 0 and 1, where 0 is completely transparent and 1 is completely opaque.

With a fade animation, the fading object's opacity is gradually increased or reduced from the starting opacity to the end opacity. This example will demonstrate a fade-out animation, from 100% opacity to 0% opacity, over 10 "steps":

<script language="Javascript">
..

//Detect browser for later use
browser = undefined;

if(navigator.userAgent.indexOf("MSIE")!=-1)
  browser = "IE";
else
  browser = "Mozilla";

//Called to fade element
function fade(element)
{
  //We will fade the object in 10 steps
  var steps = 10;
  
  //Set the starting opacity
  setOpacity(element, 1);
  
  //Loops the timer function
  for(i=0; i<steps; ++i) {
    setTimeout(function(){fadeCallback(element);}, (30*i));
  }
}

//Callback to timer function
function fadeCallback(element)
{
  //Get the current opacity
  var opacity=getOpacity(element);
  
  //Set the new opacity
  setOpacity(element, opacity-0.1);
}

//Gets an element's opacity
function getOpacity(element)
{
  var opacity = null;
  
  //Get the opacity based on the current browser used
  if(browser=="IE") {
    filter = element.style.filter;
    if(filter) {
      alpha = filter.split("alpha(opacity=");
      opacity = alpha[1].substr(0,(alpha[1].length-1))/100;
    }
  }
  else {
    opacity = element.style.opacity;
  }
    
  return opacity;
}

//Sets an element's opacity
function setOpacity(element, o)
{
  //Set the opacity based on the current browser used
  if(browser=="IE") {
    element.style.filter = "alpha(opacity=" + (o*100) + ")";
  }
  else {
    element.style.opacity = o;
  }
}

..
</script>

The animation can then be run by calling fade(element) where element is the reference to the element, for example:

<div style="width: 50px; height: 50px; background-color: red;" onClick="fade(this);">
</div>

which will fade the DIV out when it is clicked on.

As this may be hard to digest I'll break each section down into more manageable chunks:

..

if(navigator.userAgent.indexOf("MSIE")!=-1)
  browser = "IE";
else
  browser = "Mozilla";

..

This first piece of code is merely a simple way to detect whether the browser used is IE or "Mozilla" (being a non-IE browser), as this is used later when retrieving or setting the opacity of an element. The code uses the navigator.userAgent variable, which returns the current browser identifier string, and then checks whether it contains "MSIE", as this would mean that the current browser is Internet Explorer. If it is not, then it is irrelevant which browser is being used because they will all use another, standard opacity style.

The fade() Function

..

function fade(element)
{
  //We will fade the object in 10 steps
  var steps = 10;
  
  //Set the starting opacity
  setOpacity(element, 1);
  
  //Loops the timer function
  for(i=0; i<steps; ++i) {
    setTimeout(function(){fadeCallback(element);}, (30*i));
  }
}

..

This function is called to fade an element. It takes one argument, element, which is the handle to the element which is to be faded. The setTimeout() function is also used here. It is called in a loop to call the fadeCallback() function, which will change the opacity of the fading element. (30*i) is given as the number of milliseconds so that the fadeCallback() is called every 30 milliseconds. The element's opacity is set to 1 as a starting opacity. Also note that the callback function has function() { .. } around it. This is because as the function has arguments applied to it then if it was simply written as fadeCallback(element) then the function would be called immediately and not set as the timer function.

The fadeCallback() Function

..

function fadeCallback(element)
{
  //Get the current opacity
  var opacity=getOpacity(element);
  
  //Set the new opacity
  setOpacity(element, opacity-0.1);
}

..

This function is the callback function called by the setTimeout() function. It retrieves the current opacity of the element being faded, then sets the new opacity by decreasing the current opacity by 0.1.

The getOpacity() Function

..

function getOpacity(element)
{
  var opacity = null;
  
  //Get the opacity based on the current browser used
  if(browser=="IE") {
    filter = element.style.filter;
    if(filter) {
      alpha = filter.split("alpha(opacity=");
      opacity = alpha[1].substr(0,(alpha[1].length-1))/100;
    }
  }
  else {
    opacity = element.style.opacity;
  }
    
  return opacity;
}

..

This function gets the current opacity of the element being faded. As previously mentioned, IE and Mozilla-based browsers handle opacity differently, so this function uses the previously set browser variable to determine which method to use. The opacity is then returned for use, with a scale between 0 and 1 (where 0 is completely transparent and 1 is completely opaque).

The setOpacity() Function

..

function setOpacity(element, o)
{
  //Set the opacity based on the current browser used
  if(browser=="IE") {
    element.style.filter = "alpha(opacity=" + (o*100) + ")";
  }
  else {
    element.style.opacity = o;
  }
}

..

This function sets the opacity of the element being faded. Like the getOpacity() function, it differentiates between the IE and Mozilla-based browser opacity handling using the previously set browser variable.

As previously mentioned, as this is only an introductory article, I have only covered how to fade out elements, however, the principles for fading in elements are the same, except that the starting opacity is 0 and the opacity is increased at each step.

setTimeout() or setInterval()?

What is the difference?

There are two key functions in Javascript that can be used to animate objects. The first of these, which has already been demonstrated, is setTimeout(), and the other is setInterval(). They both perform similar functions, but have a subtle difference. The part which they have in common is that they both call a function after a specified number of milliseconds has elapsed, but setTimeout() calls this function after the period of time has elapsed only once, however setInterval() calls the function after every x number of milliseconds has passed, on a loop, until the clearInterval() function is called.

So which function is the best to use? After experimenting with both methods, I have found them to be both equally as useful, and both require code to be written to check whether the animation has finished or not; for setTimeout(), the fade() function calculates how many times it must be called, based on the number of steps, and for setInterval(), code in the callback function determines whether the animation has finished or not. For the sake of this simple animation demonstration, setTimeout() is more appropriate, as the number of times that the animation callback function has been called is calculated in the fade() function, whereas with setInterval(), whether or not the animation has finished is determined in the animation callback function, and the timer ID must be stored (see the example below). However, I have found that for larger scale, more complex animations, the setInterval() function is more appropriate, especially for such methods as varying the opacity increment/decrement per step.

An Example Using setInterval()

An example of an animation using the setInterval() function is:

..

//Detect browser for later use
..

//Stores the setInterval() ID
timer = null;

//Called to fade element
function fade(element)
{
  //Set the timer interval to 30ms and store the setInterval() ID
  timer = setInterval(function(){fadeCallback(element);}, 30);
}

//Callback to timer function
function fadeCallback(element)
{
  //Get the current opacity
  var opacity=getOpacity(element);
  
  //Clears the interval if at the end of the animation
  if((opacity-0.1)==0)
    clearInterval(timer);
  
  //Set the new opacity
  setOpacity(element, opacity-0.1);
}

//Gets an element's opacity
function getOpacity(element)
{
  ..
}

//Sets an element's opacity
function setOpacity(element, o)
{
  ..
}

..

This example is very similar to the example that uses the setTimeout() function, but has a few distinct changes. As you can see, the code to determine whether the animation has completed is included in the animation callback function:

if((opacity-0.1)==0)
  clearInterval(timer);

This utilises the clearInterval() function, which deletes a timer created with the setInterval() function, it's only argument being the ID of the timer created. As shown in the example, the timer ID is returned when the setInterval() function is called:

timer = setInterval(function(){fadeCallback(element);}, 30);

As you can see, the setInterval() ID must be stored so that the timer can be cleared after use.

Conclusion

After reading this article, you should be able to:

  • Understand how Javascript timers work
  • Be able to implement a basic object animator
  • Understand the difference between the setTimeout() and setInterval() functions

History

23rd July 2008: Unmodified first copy

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Perspx

United Kingdom United Kingdom
My Blog

Perspx, or Alex Rozanski, is a teenage programmer currently residing in London. He has been programming for approximately 8 years.

He now spends most of his time with web development - trying to maintain sanity with browser incompatibilities - and dabbling with Cocoa, writing applications for Mac OS X in Objective-C. He plans to also broaden his horizons to the iPhone platform in the near future.

Between studying and programming he plays the guitar, enjoys a good horror film, heavy metal music, and tries to plan his future career path.


Comments and Discussions

 
QuestionFading in PinmemberSwajn20-Jun-12 9:09 
GeneralGreat PinmemberMohammad Dayyan2-Aug-08 11:13 
Thank you for sharing it .
GeneralRe: Great PinmemberPerspx22-Aug-08 4:29 
GeneralEasy To understand PinmemberCybercockroach27-Jul-08 14:01 
GeneralRe: Easy To understand PinmemberPerspx28-Jul-08 2:18 
GeneralSuggestion Pinmemberfwsouthern24-Jul-08 19:05 
GeneralRe: Suggestion PinsitebuilderUwe Keim24-Jul-08 20:21 
GeneralRe: Suggestion PinmemberPerspx24-Jul-08 23:34 
GeneralRe: Suggestion Pinmemberfwsouthern25-Jul-08 2:14 
GeneralRe: Suggestion PinmemberPerspx25-Jul-08 3:57 
GeneralRe: Suggestion SMIL PinmemberMember 314367928-Jul-08 20:54 
GeneralRe: Suggestion SMIL PinmemberPerspx29-Jul-08 10:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140827.1 | Last Updated 24 Jul 2008
Article Copyright 2008 by Perspx
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid