3

I seem to regularly write jQuery code of a pattern similar to this:

Fade Out ==> Do Something Behind the Scenes ==> Fade In
Illustrated below:

/// <reference path="jquery-1.4.2.js" />
/// <reference path="jquery-1.4.2-vsdoc.js" />
/// <reference path="jquery.validate-vsdoc.js" />
var fade = "slow";

$(document).ready(function () {

    // Some event occurs
    $("#Trigger").change(function () {
        var id = $(this).find(":selected").val();        

        // Fade out target while I do something
        $("#Target").fadeOut(fade, function () {
            if (id != "") {

                // Do Something
                $("#Target").load(
                    "/Site/Controller/Action/"+id, null,
                    function () {

                        // Fade in Target
                        $("#Target").fadeIn(fade);
                    });
            }
        });
    });
});

This works fine, but the callback hierarchy gets pretty deep and I'm just wondering if there's an easier way to do this or a better technique that doesn't result in so many levels of callbacks

TJB
  • 13,367
  • 4
  • 34
  • 46
  • Is the Do Something step pretty instant, or does it take some time? – hookedonwinter Jul 16 '10 at 20:51
  • Hm, it could take time depending, most times it will be pretty quick but i can't garauntee that it will always be instant – TJB Jul 16 '10 at 21:49
  • Shouldn't `$("#Target").fadeIn(fade)` be called regardless of whether `id != ''`? – Eric Jul 17 '10 at 10:39
  • In this particular case no, the effect will be that if the user makes a valid selection the relevant data will be shown, otherwise the target will stay blank. But in some other cases it may be preferible to always fade back in – TJB Jul 17 '10 at 19:20

2 Answers2

6

Use jQuery's .queue

$("#Target")
    .fadeOut()
    .queue(function() {
        if (id != "")
            // Do Something
            $(this).load(
                "/Site/Controller/Action/"+id, null,
                $(this).dequeue
            );
        else
            $(this).dequeue();
    })
    .fadeIn()
Eric
  • 95,302
  • 53
  • 242
  • 374
1

With jQuery.queue() you can append multiple commands to execute in sequence. How you use it depends on what you want to do. Here's two solutions:

1) targeting a single element:

$('#label')
    .fadeOut()                     //animate element
    .queue(function() {            //do something method1
        ...your code here...
        $(this).dequeue //dequeue the next item in the queue
    })
    .queue(function (next) {          //do something method2
        ...your code here...
        next(); //dequeue the next item in the queue
    })
    .delay(5000)                   //do lots more cool stuff.
    .show("slow")
    .animate({left:'+=200'},2000)
    .slideToggle(1000)
    .slideToggle("fast")
    .animate({left:'-=200'},1500)
    .hide("slow")
    .show(1200)
    .slideUp("normal", runIt)
    .fadeIn()

2)You could look at it another way- create a queue function which does many things, and then execute it whenever you want:

var $header = $("#header");
var $footer = $("#footer");

function runIt() {
    $header.queue(function(next){
        ...do something...
        next();
        }
    $header.queue(function(next){
        functionABC(variable, next);
        })
    $footer.animate({left:'+=200'},2000);
    $("#left").slideToggle(1000);
    $(".class1").slideToggle("fast");
    $(".class2").animate({left:'-=200'},1500);
    $("whatever").delay(3000);
    $(".class3").hide("slow");
      }

    runIt();    //execute it now, or...

    $(window).load(function() {  //execute it after the page loads!
       runIt();
    })

You can also use the queue:false variable. This means the queue wont wait for this operation to finish, so will start the next straight away. Its useful to do two animations together:

function runIt() {
    $("#first").animate(
        {width: '200px'},
        {duration:2000, queue:false}
    );
    $footer.animate(
        {left:'+=200'},
        2000
    );
}

With AJAX, queues get a bit more complicated. Check out this post:

AJAX Queues on this post.

Community
  • 1
  • 1
Patrick Keane
  • 663
  • 3
  • 19
  • 41