Quantcast
Viewing all articles
Browse latest Browse all 10

Creating a jQuery animation from a single sprite image

Image may be NSFW.
Clik here to view.
jquery-sprite-animation

Old days

In old days it was quite common to see GIF animations all over the net. Those files with .gif extension containing a sequence of images in a loop.

Nowadays, apart from being used in adverts and banners, is not that cool anymore. I would even say: ugly. Having a loop of images without ending is tired and boring, besides from the fact that the available color palette is quite small and doesn’t allow some graduates or cool transparencies. (mmmmm I love them…)

Nowadays animations

Yet, we still want to show some kind of animation in our websites. CSS 3 (not supported for the not so older versions of IE…) makes it easy as well as Javascript with the help of popular libraries such as jQuery or Prototype.

So, what could we do if we want to show a proper animation?

A simple and quick solution

We can still making use of the GIF idea: a sequence of images.
But in this case, we will be able to use any image format with a proper quality and the animation will have an end. This is: we won’t use .gif format!

We can create 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 animation = setInterval(function(){
    var position =  -1 * (cont*imgHeight);
    $('#container').find('img').css('margin-top', position);
    
    cont++;
    if(cont == numImgs){
        clearInterval(animation);
    }
},100);

HTML

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

CSS

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

Image may be NSFW.
Clik here to view.
View demo

And for commodity, I give you also the fiddle:
http://jsfiddle.net/aTqGw/1/

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


Viewing all articles
Browse latest Browse all 10

Trending Articles