Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

queue a number of effects synchronously with jquery

Is there are more readable way to queue a number of asynchronous effects that they are executed synchronously?

var element1 = $('#div1');
var element2 = $('#div2');

$(element2).hide();
$(element1).on('click',function(){   
    $(element1).fadeOut(1000,function(){
        $(element2).fadeIn(1000, function(){
            $(element2).hide();
            alert('hello');
        });
    });
}); 
like image 556
Elisabeth Avatar asked Jan 22 '26 06:01

Elisabeth


2 Answers

You can prevent the ever-deeper nesting effect if you use a promise-based system.

$.when(
    $(element1).fadeOut(1000)
).then(function () {
    return $(element2).fadeIn(1000);
}).then(function () {
    return $(element2).hide();
}).then(function () {
    return $(element1).fadeIn(1000);
}).then(function () {
    return $(element1).fadeOut(1000);
});

Demo: http://jsfiddle.net/tYhNq/1

You'll notice this makes it very easy to change the order of the animations.

The "trick" is that the $.when() method returns the promise object associated with the first animation, so then you can just chain a bunch of .then() calls, noting that each then() callback should return the result of its animation.

Of course you can directly chain animations on the same element, e.g. .fadeIn(100).fadeOut(100)...

like image 130
nnnnnn Avatar answered Jan 24 '26 21:01

nnnnnn


This problem is called "callback hell". In NodeJS you have async module option to "escape" from it.

I didn't find a correspondent option in jQuery.

My suggestion is to create one function for every effect, like bellow:

var element1 = $('#div1');
var element2 = $('#div2');

$(element2).hide();

var finished = function () { console.log(":-)"); }
var hide = function () { element2.hide(); finished(); }
var fadeIn = function () { element2.fadeIn(1000, hide); }
var clicked = function () { element1.fadeOut(1000, fadeIn); }

$(element1).on('click', clicked);

JSFIDDLE

like image 25
Ionică Bizău Avatar answered Jan 24 '26 22:01

Ionică Bizău



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!