jQuery: PNG animation

In this post I'll show you how to create a simple PNG animation with jQuery. There's nothing difficult with this: all we need is a PNG image divided into several sequential frames that will be progressively revealed by adjusting the horizontal value of the CSS background-position property. Here's our image:

Our image is 300 x 127 pixels wide. Each frame is about 60 pixels wide, so our initial styles will be the following:

#anim {
 height: 127px;
 width: 60px;
 background: url(walker.png) no-repeat 0 0;
 margin: 0 auto;

Now we need to create an array and store there all the frame positions of our animation. Then we loop through this array using an index value within a JavaScript timer that makes our animation enter in an infinite loop:

$(function() {

  var steps = [0, 60, 110, 171, 230, 300];
  var index = -1;
  var interval = setTimeout(function() {
     if(index == 5) {
       index = 0;
    $('#anim').css('backgroundPosition', '-' + steps[index] + 'px 0px');
    setTimeout(arguments.callee, 100);
  }, 25);


We use a progressive negative value for the CSS background-position property. You can see the demo below.


Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

2 thoughts on “jQuery: PNG animation”

  1. Very interesting approach. I'm wondering though why you havent chosen individial images for each frame to loop through instead? Performance benefit?

Leave a Reply

Note: Only a member of this blog may post a comment.