Question

I am making use of Jonathan Sampson's answer for my jquery busy loader. it works 100% and detects any jquery posting or the like and shows the loader.

my problem is that most times I want the user to wait when I fetch info from the database so happy for the loader to appear.

What I want however, is for certain functions only for the loader not to show when I save info to the database.

the fiddle can be found here

for example, the below causes the loader to run. how can I modify this so mockjax knows not to run for this function only?

$(document).on("click", function(){
    $.get("/mockjax");        
});

Thanks for the help as always.

Was it helpful?

Solution

Short version (with code)

Click the heading - Animation

Click the paragraph - No Animation

http://jsfiddle.net/hPS2v/

$.ajax({
    url: "/mockjax",
    type: "GET",
    global: false //This is the key
});

--

The slightly longer version

There is a great variable available in the $.ajax() method which let's you stop ajax events from firing (but not the ajax itself). This is called global. From the docs

global (default: true)

Type: Boolean

Whether to trigger global Ajax event handlers for this request. The default is true. Set to false to prevent the global handlers like ajaxStart or ajaxStop from being triggered. This can be used to control various Ajax Events.

With this in mind, I have slightly changed your code a little to demonstrate how we can make this work.

1) Moved the AJAX call into a function with 2 parameters: URL and eventTrigger. Basically we want the URL to be "/mockajax", and the eventTrigger to be true or false (depending on if and when you want to show your animation)

2) I took the event handler off the $(document) and added 2 events to the heading tags and the p tags so I can demonstrate the AJAX working in 2 places with the same code (1 with and 1 without an animation)

Hope this helps!

OTHER TIPS

You can use a variable as a flag which denotes your preference of not showing the loader.

//let say, showLoader, by default true
var showLoader = true;

Now, add this to your ajax setup as required.

$(document).on({
    ajaxStart: function () {
        // if showLoader true, then shows loading image
        if (showLoader)
            $body.addClass("loading");
    },
    ajaxStop: function () {
        $body.removeClass("loading");
        // set showLoader to true
        showLoader = true;
    }
});

Change showLoader state as required by you.

$(document).on("click", function (e) {
    // if target element is anchor tag, then do not show loading image - example
    if (e.target.tagName === 'A') {
        showLoader = false;
    }
    $.get("/mockjax");
});

JSFiddle: http://jsfiddle.net/VpDUG/5177/

Hope, it helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top