Years ago it was quite common to see GIF animations all over the net. Basically we call GIF images to any image using the .gif extension. The Gif format provides a way to display a sequence of images one after another creating the illusion of an animation, same as the way cartoon movies were made in the past.

javascript sprite image

Old days

Currently the use of Gif animations in websites has dramatically decreased, but why? Although you can actually have GIF animations with end (no loop), the fact that the color palette is so reduced (up to 256 per frame) has taken an important role on it. Color graduations were not looking good at all and many transparencies were being affected by this restriction.

The modern way

We still want to show some animation in our websites from time to time. For some, we take courage and make use of CSS3 animations (and hopefully provide some fallback for non css3 browsers…)

But we can also go for another option that provides us with the freedom of using images for our animations with all this implies. (remember the cartoons movies? ) With just the use of Javascript we can have a pretty decent “movie”.

A simple and quick solution

First, design your sequence of images. Remember now we will be able to use any image format (super quality images!). And please, do not use GIF format here or you won’t gain anything from this! :)

So, basically we will be creating a simple sprite of images and then using jQuery move the position of the image inside a container:

Javascript

var imgHeight = 360;
var numImgs = 67;
var cont = 0;
var img = $('#container').find('img');

var animation = setInterval( moveSprite,100);

function moveSprite(){
    img.css('margin-top', -1 * (cont*imgHeight));

    cont++;
    if(cont == numImgs){
        clearInterval(animation);
    }
}

HTML

<div id="container">
    <img src="https://d3ckw5pamzrtgd.cloudfront.net/assets/animations/care/animation.png" alt="My super animation"/>
</div>

CSS

#container{
    width:100%;
    height: 350px;
    display:block;
    overflow:hidden;
}

Demo

Here’s a fiddle in case you want to play a bit.

The sprite image I used for the example was taken from http://onlinedepartment.nl/.