March 28, 2012

jQuery function chaining unrelated objects

Question by jim tollan

I have of course searched SO for an answer to my ‘specific’ question but haven’t found anything that allows me to reach my desired goal. Basically, I’d like to be able to chain together function calls with the ability to add a ‘delay’ between those calls being issued. I’m figuring that something along the lines of a setTimeout() chain will be required. However, as these calls are aysnchronys, I obviously can’t simply chain those together and hope for a result. I did see reference to the built in jQuery queue and dequeue functions and figured that something might work based on that. Thus far, I’ve not been able to concoct anything that gets close to my requirement.

I’ve created a very basic example that demonstrates what I’m trying to achieve by chaining here (btw – jsfiddle is being a bit slow today):

http://jsfiddle.net/jimibt/wZeTT/

this uses nested setInterval calls, therefore is nasty and doesn’t scale. My nirvana would be a jquery extension method that had the following syntax (1st param being the function, 2nd param being the setTimout value delay):

$().chain($('#strap1').fadeIn(1300), 500)
     .chain($('#strap2').fadeIn(1300), 500)
     .chain($('#strap3').fadeIn(1300), 500)
     .start();

Now I know that there is a delay() funtion in jquery, but this only works (to my knowledge) as part of a chain against a single selector and thus can’t be used to chain together multiple unconnected elements as per my example. I did see this linked SO question that is CLOSE to what I was hoping for, but still not wrapped up in the way I’d like:

Chaining jQuery animations that affect different elements

Any thoughts??

Answer by Starx

You can use callbacks like this

$('#strap1').delay(500).fadeIn(1300,function(){
    $('#strap2').delay(500).fadeIn(1300,function(){
        $('#strap3').delay(500).fadeIn(1300);
    });
});

Usage [demo]

$('#strap1').delay(500).fadeIn(1300,function(){
    $('#strap2').delay(500).fadeIn(1300,function(){
        $('#strap3').delay(500).fadeIn(1300, function() {
            $('#strapline').css({
                'color': '#fff'
            }).animate({
                'color': color
            }, 3000);            
        });
    });
});

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!