jQuery: animating letters with chained animations

Letters, characters, chunks of text and similar strings can all be animated by jQuery. An important aspect in this case is the correct animation sequence: first, delay, second, delay and so on. To accomplish this task, we can use jQuery's methods for creating animation chains. Let's see the details.

We have five different letters contained within a block:

<h1 id="wrapper"><span>L</span><span>o</span><span>r</span><span>e</span><span>m</span></h1>​

Each letter will be absolutely positioned, as follows:

h1 {
    text-align: center;
    font: normal 3em Arial, sans-serif;
    width: 10em;
    height: 2em;
    position: relative;
    margin: 1em auto;
}

h1 span {
    position: absolute;
    width: 2em;
    height: 2em;
    background: #333;
    color: #fff;
    text-align: center;
    line-height: 2;
    border-radius: 50%;
}
span:nth-child(1) { left: 0; }
span:nth-child(2)  { left: 2em; }
span:nth-child(3) { left: 4em; }
span:nth-child(4) { left: 6em; }
span:nth-child(5) { left: 8em; }
​

With jQuery, we'll first collect the original left offsets of the letters. Then we'll make them disappear from the screen by using a negative offset. Finally, we'll create chained animations by using the queue() and dequeue() methods:

var animateChars = function() {

    var positions = [];
    var delay = 0;

    $('span', '#wrapper').each(function(i) {
        positions[i] = $(this).position().left;
    });

    $('span', '#wrapper').css('left', '-1000em');

    $('span', '#wrapper').each(function(i) {

        var $span = $(this);

        $span.queue('chars', function(next) {


            $span.delay(delay).animate({
                left: positions[i]
            }, 1000, next);

        });

        $span.dequeue('chars');
        
        delay += 500;

    });
};

animateChars();​

You can see the demo below.

Demo

Live demo

Back to top