Tigraine

Daniel Hoelbling-Inzko talks about programming

jQuery: Execute once animation finished

Posted by Daniel Hölbling on August 21, 2011

Good JavaScript almost forces you into learning async programming and jQuery animations is no different. Everything in jQuery supports callbacks because the stuff you do is in most cases done on the background while your script continues to run.

But as with most stuff, there are many ways of going about this:

Completed Callbacks

    $('#item').fadeOut('slow', function () {
        console.log('animation finished');
    });

The problem with this approach is that it gets rather tedious to queue stuff together if you want to do say three things in order.

Let's say you want to a fadeOut animation then add a cssClass, start another animation and once that one is finished remove the cssClass again. Using callbacks this looks rather ugly:

    $('#item').fadeOut('slow', function () {
        var foo = $('#foo');
        foo.addClass('myclass');
        $('#item2').fadeIn('slow', function () {
          foo.removeClasS('myclass');
        }
    });

As you can see, two nested callbacks is really not that readable and almost confusing.. That's why there is a better way to do this:

The fx Queue

jQuery uses a queue for all it's animations. That's the magic behind this nice syntax:

    $('#item').fadeIn().fadeOut();

If you run this code it will first fade the item in and only once it's completely visible it will start the fadeOut animation.

Problem with this is that it looks nice in it's syntax, but can't be mixed with the regular jQuery methods. Something like

$('#item').fadeIn().removeClass('active').fadeOut();
will not work simply because you removeClass will be executed instantly while fadeIn and fadeOut will be queued for later execution by the effects (fx) queue.

In that case you can hook into the queue yourself by using the .queue() method:

    $('#item').fadeIn().queue(function (next) {
        $(this).removeClass('active');
        next(); //Important to continue running the queue
    }).fadeOut();

Hope this helps!

Filed under javascript, jquery
comments powered by Disqus

My Photography business

Projects

dynamic css for .NET

Archives

more