Skip to content
Fix Code Error

How to show loading spinner in jQuery?

March 13, 2021 by Code Error
Posted By: Edward Tanguay

In Prototype I can show a “loading…” image with this code:

var myAjax = new Ajax.Request( url, {method: 'get', parameters: pars, 
onLoading: showLoad, onComplete: showResponse} );

function showLoad () {
    ...
}

In jQuery, I can load a server page into an element with this:

$('#message').load('index.php?pg=ajaxFlashcard');

but how do I attach a loading spinner to this command as I did in Prototype?

Solution

There are a couple of ways. My preferred way is to attach a function to the ajaxStart/Stop events on the element itself.

$('#loadingDiv')
    .hide()  // Hide it initially
    .ajaxStart(function() {
        $(this).show();
    })
    .ajaxStop(function() {
        $(this).hide();
    })
;

The ajaxStart/Stop functions will fire whenever you do any Ajax calls.

Update: As of jQuery 1.8, the documentation states that .ajaxStart/Stop should only be attached to document. This would transform the above snippet to:

var $loading = $('#loadingDiv').hide();
$(document)
  .ajaxStart(function () {
    $loading.show();
  })
  .ajaxStop(function () {
    $loading.hide();
  });
Answered By: nickf

Related Articles

  • Attach the events ajaxStart() and ajaxStop() only to the…
  • Reference — What does this symbol mean in PHP?
  • Downloading jQuery UI CSS from Google's CDN
  • jQuery Mobile: document ready vs. page events
  • jQuery.active function
  • How to use Servlets and Ajax?
  • Am I paranoid? "Brutally" big Polymer website after…
  • Reference - What does this regex mean?
  • render function or template not defined in component:…
  • Using one iron-ajax element for multiple requests

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

RedirectToAction with parameter

Next Post:

Google Maps JS API v3 – Simple Multiple Marker Example

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Get code errors & solutions at akashmittal.com
© 2022 Fix Code Error