Rectangle 27 1

How can I create a "Please Wait, Loading..." animation using jQuery?


$body = $("body");

$(document).on({
    ajaxStart: function() { $body.addClass("loading");    },
     ajaxStop: function() { $body.removeClass("loading"); }    
});
/* Start by setting display:none to make this hidden.
   Then we position it in relation to the viewport window
   with position:fixed. Width, height, top and left speak
   for themselves. Background we set to 80% white with
   our animation centered, and no-repeating */
.modal {
    display:    none;
    position:   fixed;
    z-index:    1000;
    top:        0;
    left:       0;
    height:     100%;
    width:      100%;
    background: rgba( 255, 255, 255, .8 ) 
                url('http://i.stack.imgur.com/FhHRx.gif') 
                50% 50% 
                no-repeat;
}

/* When the body has the loading class, we turn
   the scrollbar off with overflow:hidden */
body.loading {
    overflow: hidden;   
}

/* Anytime the body has the loading class, our
   modal element will be visible */
body.loading .modal {
    display: block;
}
<div class="modal"><!-- Place at bottom of page --></div>

I had to use .bind() instead of .on() as we are using jQuery 1.5.1!

I love when something just works. There's a reason @JonathanSampson has 68k rep.

I'd recommend using the plugin that plugins to the plugins to make sure they're all plugged in.

Let's create an element that we can show/hide anytime we're making an ajax request:

Let's start by getting us a nice "loading" animation from http://ajaxload.info I'll be using

That's it! We're attaching some events to the body element anytime the ajaxStart or ajaxStop events are fired. When an ajax event starts, we add the "loading" class to the body. and when events are done, we remove the "loading" class from the body.

This is the most in depth solution although I'd recommend you use a centering plugin which centers the preloader around a page element (i.e. body, #element, or .element)

You could do this various different ways. It could be a subtle as a small status on the page saying "Loading...", or as loud as an entire element graying out the page while the new data is loading. The approach I'm taking below will show you how to accomplish both methods.

Note
Rectangle 27 0

How can I create a "Please Wait, Loading..." animation using jQuery?


$(document).ajaxStart(function(){}).
$(document).ajaxStart(function(){
    $('#loading').show();
 }).ajaxStop(function(){
    $('#loading').hide();
 });
.ajaxStart
<div id="loading">
  <p><img src="loading.gif" /> Please Wait</p>
</div>
ajaxStart

...and it's brother, the ajaxStop event

Along with what Jonathan and Samir suggested (both excellent answers btw!), jQuery has some built in events that it'll fire for you when making an ajax request.

Attach a function to be executed whenever all AJAX requests have ended. This is an Ajax Event.

Jonathan's answer was very in-dept, but this for me was the best for its simplicity.

Show a loading message whenever an AJAX request starts (and none is already active).

Together, they make a fine way to show a progress message when any ajax activity is happening anywhere on the page.

Note
Rectangle 27 0

How can I create a "Please Wait, Loading..." animation using jQuery?


$(document).ready(function () {

    $('#spinner').bind("ajaxSend", function() {
        $(this).show();
    }).bind("ajaxComplete", function() {
        $(this).hide();
    });

});
<div id="spinner">
  <img src="images/spinner.gif" alt="Loading" />
</div>

Ah - as I understood, you wanted a loading image to be shown whenever you were making AJAX requests. If you simply want a "please wait, loading..." animation to be shown until the page has fully loaded, you could have a loading div in the page and then hide it in your $(document).ready block.

Can someone please explain what AJAX has to do with this? Can't I simply manage this all within the page without accessing the server with AJAX... Or am I missing here something? Thanks.

For example, create the following div:

Now, whenever you send Ajax requests, the #spinner div will be shown. When the request is complete, it'll be hidden again.

Set it to display: none in your stylesheets. You can style it whatever way you want to. You can generate a nice loading image at Ajaxload.info, if you want to.

Simply add this Javascript block to the end of your page before closing your body tag or wherever you see fit.

Then, you can use something like the following to make it be shown automatically when sending Ajax requests:

jQuery provides event hooks for when AJAX requests start and end. You can hook into these to show your loader.

Note
Rectangle 27 0

How can I create a "Please Wait, Loading..." animation using jQuery?


$('#form').submit(function() {
    $.ajax({
        url: '/whatever.php',
        beforeSend: function() { $('#wait').show(); },
        complete: function() { $('#wait').hide(); }
    });
    return false;
});
$('#wait').ajaxStart(function() {
    $(this).show();
}).ajaxComplete(function() {
    $(this).hide();
});

A) Manually show and hide the image:

As far as displaying a DIV with this image when a request begins, you have a few choices:

As far as the actual loading image, check out this site for a bunch of options.

C) Use individual callbacks for a particular request:

Something to note: if you cant modify the HTML to add the loading img element, you can do it as a background-image on the button using CSS e.g. input.loading-gif{background:url('images/loading.gif');} and then apply the class with jQuery e.g. $('#mybutton').addClass('loading-gif'); The only gotcha is that this will only request the gif when the submit button is clicked, which is normally too late, so you need to pre-cache it, which is easy with jQuery e.g. (new Image()).src = "images/loading.gif";

This site has a larger and in my opinion nicer selection of loaders with more customization options preloaders.net

Using this the element will show/hide for any request. Could be good or bad, depending on the need.

Note
Rectangle 27 0

How can I create a "Please Wait, Loading..." animation using jQuery?


$.load(
     'http://example.com/myurl',
     { 'random': 'data': 1: 2, 'dwarfs': 7},
     function (responseText, textStatus, XMLHttpRequest) {
         hideLoadingImage();
     }
);

// this will be run immediately after the AJAX call has been made,
// not when it completes.
showLoadingImage();
function showLoadingImage() {
    $('#yourParentElement').append('<div id="loading-image"><img src="path/to/loading.gif" alt="Loading..." /></div>');
}

function hideLoadingImage() {
    $('#loading-image').remove();
}

Samir Talwar: A heavy JavaScript application actually. Thanks, I get the idea.

Secondly, this will only hide the loading image on a successful AJAX call. To handle the error states, you'll need to look into $.ajax, which is more complex than $.load, $.get and the like, but a lot more flexible too.

Thanks for the reply. But tell me, why do I need to use AJAX at all? Can't I simply track down it all in the page itself?

This has a few caveats: first of all, if you have two or more places the loading image can be shown, you're going to need to kep track of how many calls are running at once somehow, and only hide when they're all done. This can be done using a simple counter, which should work for almost all cases.

Understandable. In that case, just call showLoadingImage before you start and hideLoadingImage after you finish. Should be fairly simple. You may need to stick some sort of setTimeout call in to make sure the browser actually renders the new <img> tag though - I've seen a couple of cases where it doesn't bother until the JavaScript has finished executing.

What exactly do you want to track? Unless you're requesting information after the page has loaded (and AJAX is pretty much the only way to do that without using a plugin), why would you need a "loading" image at all?

You can grab an animated GIF of a spinning circle from Ajaxload - stick that somewhere in your website file heirarchy. Then you just need to add an HTML element with the correct code, and remove it when you're done. This is fairly simple:

You then just need to use these methods in your AJAX call:

Note
Rectangle 27 0

How can I create a "Please Wait, Loading..." animation using jQuery?


.modal {
display:    none;
position:   fixed;
z-index:    1000;
top:        0;
left:       0;
height:     100%;
width:      100%;
background: rgba( 255, 255, 255, .8 ) 
            url('http://i.stack.imgur.com/FhHRx.gif') 
            50% 50% 
            no-repeat;
opacity: 0.80;
-ms-filter: progid:DXImageTransform.Microsoft.Alpha(Opacity = 80);
filter: alpha(opacity = 80)};

Edited because the multiple 'background-' lines didn't work, but the single background statement works correctly.

Note
Rectangle 27 0

How can I create a "Please Wait, Loading..." animation using jQuery?


$('#form').submit(function() {
    $.ajax({
        url: '/whatever.php',
        beforeSend: function() { $('#wait').show(); },
        complete: function() { $('#wait').hide(); }
    });
    return false;
});
$('#wait').ajaxStart(function() {
    $(this).show();
}).ajaxComplete(function() {
    $(this).hide();
});

A) Manually show and hide the image:

As far as displaying a DIV with this image when a request begins, you have a few choices:

As far as the actual loading image, check out this site for a bunch of options.

C) Use individual callbacks for a particular request:

Something to note: if you cant modify the HTML to add the loading img element, you can do it as a background-image on the button using CSS e.g. input.loading-gif{background:url('images/loading.gif');} and then apply the class with jQuery e.g. $('#mybutton').addClass('loading-gif'); The only gotcha is that this will only request the gif when the submit button is clicked, which is normally too late, so you need to pre-cache it, which is easy with jQuery e.g. (new Image()).src = "images/loading.gif";

This site has a larger and in my opinion nicer selection of loaders with more customization options preloaders.net

Using this the element will show/hide for any request. Could be good or bad, depending on the need.

Note
Rectangle 27 0

How can I create a "Please Wait, Loading..." animation using jQuery?


$(function(){
    $('#submit').click(function(){
        $('#submit').hide();
        $("#form .buttons").append('<img src="assets/img/loading.gif" alt="Loading..." id="loading" />');
        $.post("sendmail.php",
                {emailFrom: nameVal, subject: subjectVal, message: messageVal},
                function(data){
                    jQuery("#form").slideUp("normal", function() {                 
                        $("#form").before('<h1>Success</h1><p>Your email was sent.</p>');
                    });
                }
        );
    });
});

This would make the buttons disappear, then an animation of "loading" would appear in their place and finally just display a success message.

Note
Rectangle 27 0

How can I create a "Please Wait, Loading..." animation using jQuery?


$.load(
     'http://example.com/myurl',
     { 'random': 'data': 1: 2, 'dwarfs': 7},
     function (responseText, textStatus, XMLHttpRequest) {
         hideLoadingImage();
     }
);

// this will be run immediately after the AJAX call has been made,
// not when it completes.
showLoadingImage();
function showLoadingImage() {
    $('#yourParentElement').append('<div id="loading-image"><img src="path/to/loading.gif" alt="Loading..." /></div>');
}

function hideLoadingImage() {
    $('#loading-image').remove();
}

Samir Talwar: A heavy JavaScript application actually. Thanks, I get the idea.

Secondly, this will only hide the loading image on a successful AJAX call. To handle the error states, you'll need to look into $.ajax, which is more complex than $.load, $.get and the like, but a lot more flexible too.

Thanks for the reply. But tell me, why do I need to use AJAX at all? Can't I simply track down it all in the page itself?

This has a few caveats: first of all, if you have two or more places the loading image can be shown, you're going to need to kep track of how many calls are running at once somehow, and only hide when they're all done. This can be done using a simple counter, which should work for almost all cases.

Understandable. In that case, just call showLoadingImage before you start and hideLoadingImage after you finish. Should be fairly simple. You may need to stick some sort of setTimeout call in to make sure the browser actually renders the new <img> tag though - I've seen a couple of cases where it doesn't bother until the JavaScript has finished executing.

What exactly do you want to track? Unless you're requesting information after the page has loaded (and AJAX is pretty much the only way to do that without using a plugin), why would you need a "loading" image at all?

You can grab an animated GIF of a spinning circle from Ajaxload - stick that somewhere in your website file heirarchy. Then you just need to add an HTML element with the correct code, and remove it when you're done. This is fairly simple:

You then just need to use these methods in your AJAX call:

Note
Rectangle 27 0

How can I create a "Please Wait, Loading..." animation using jQuery?


.modal {
display:    none;
position:   fixed;
z-index:    1000;
top:        0;
left:       0;
height:     100%;
width:      100%;
background: rgba( 255, 255, 255, .8 ) 
            url('http://i.stack.imgur.com/FhHRx.gif') 
            50% 50% 
            no-repeat;
opacity: 0.80;
-ms-filter: progid:DXImageTransform.Microsoft.Alpha(Opacity = 80);
filter: alpha(opacity = 80)};

Edited because the multiple 'background-' lines didn't work, but the single background statement works correctly.

Note