views:

673

answers:

2

I have some ajax calls on the document of a site that display or hide a progress bar depending on the ajax status

  $(document).ajaxStart(function(){ 
     $('#ajaxProgress').show(); 
    });
  $(document).ajaxStop(function(){ 
     $('#ajaxProgress').hide(); 
    });

I would like to basically overwirte these methods on other parts of the site where a lot of quick small ajax calls are made and do not need the progress bar popping in and out. I am trying to attach them to or insert them in other $.getJSON and $.ajax calls. I have tried chaining them but apparently that is no good.

$.getJSON().ajaxStart(function(){ 'kill preloader'});
A: 

Unfortunately, ajaxStart event doesn't have any additional information which you can use to decide whether to show animation or not.

Anyway, here's one idea. In your ajaxStart method, why not start animation after say 200 milliseconds? If ajax requests complete in 200 milliseconds, you don't show any animation, otherwise you show the animation. Code may look something like:

var animationController = function animationController()
{
    var timeout = null;
    var delayBy = 200; //Number of milliseconds to wait before ajax animation starts.

    var pub = {};

    var actualAnimationStart = function actualAnimationStart()
    {
        $('#ajaxProgress').show();
    };

    var actualAnimationStop = function actualAnimationStop()
    {
        $('#ajaxProgress').hide();
    };

    pub.startAnimation = function animationController$startAnimation() 
    { 
        timeout = setTimeout(actualAnimationStart, delayBy);
    };

    pub.stopAnimation = function animationController$stopAnimation()
    {
        //If ajax call finishes before the timeout occurs, we wouldn't have 
        //shown any animation.
        clearTimeout(timeout);
        actualAnimationStop();
    }

    return pub;
}();


$(document).ready(
    function()
    {
        $(document).ajaxStart(animationController.startAnimation);
        $(document).ajaxStop(animationController.stopAnimation);
    }
 );
SolutionYogi
+1  A: 

You can bind the ajaxStart and ajaxStop using custom namespace:

$(document).bind("ajaxStart.mine", function() {
    $('#ajaxProgress').show();
});

$(document).bind("ajaxStop.mine", function() {
    $('#ajaxProgress').hide();
});

Then, in other parts of the site you'll be temporarily unbinding them before your .json calls:

$(document).unbind(".mine");

Got the idea from here while searching for an answer.

EDIT: I haven't had time to test it, alas.

dalbaeb