Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Introduction to JavaScript Animation

4.30/5 (6 votes)
24 Jul 2008CPOL7 min read 1   365  
An introduction to animation in JavaScript

Image 1

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' 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 Internet Explorer and Mozilla-based browsers (Firefox, Safari, etc) but is implemented differently in both. In Internet Explorer, 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":

JavaScript
<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:

HTML
<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:

JavaScript
..

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 Internet Explorer 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

JavaScript
..

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

JavaScript
..

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

JavaScript
..

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, Internet Explorer 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

JavaScript
..

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 Internet Explorer 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:

JavaScript
..

//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:

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

This utilizes the clearInterval() function, which deletes a timer created with the setInterval() function, its 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:

JavaScript
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)