Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show loading spinner in jQuery?

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?

like image 944
Edward Tanguay Avatar asked Sep 16 '08 01:09

Edward Tanguay


People also ask

How to show loading symbol in jQuery?

Answer: Use the ajaxStart() and ajaxStop() Method You can create a preloader using the jQuery ajaxStart() and ajaxStop() method.

How to show loading spinner in JavaScript?

Step 1: Add a background with a spinner gif on top of the page, then remove them when everything is loaded. Step 2: Add a little script right after the opening body tag to start displaying the load/splash screen. Save this answer.

How to show loading image in ajax jQuery?

In not for only one ajax request, but if you want to load image on every ajax request then you can do that using bellow example. I use ajaxStart() and ajaxComplete() function for show image until All POST or GET Ajax request. this both function will execute one each $. ajax request.


2 Answers

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();   }); 
like image 155
nickf Avatar answered Oct 02 '22 08:10

nickf


For jQuery I use

jQuery.ajaxSetup({   beforeSend: function() {      $('#loader').show();   },   complete: function(){      $('#loader').hide();   },   success: function() {} }); 
like image 23
kr00lix Avatar answered Oct 02 '22 07:10

kr00lix