Stephen Cioffi
Stephen Cioffi

Reputation: 1221

Display loading animation while part of page loads via jQuery's load()

On my site I want to load "pages" dynamicly via jQuery's load() function and I would like to add a loading animation.

function loadPage(){
  $("#content").load("example.html");
}

Where would I put code to show <div id="loading"></div> while jQuery loads that content??

Thanks In Advance.

Upvotes: 3

Views: 5953

Answers (3)

Tam&#225;s Pap
Tam&#225;s Pap

Reputation: 18273

I don't know exactly what you want to do, but probably you want to load content to a div. You should create a css class:

.loading {
  background: url(loading.gif) center center;
}

and add this class to your div (after you clear it) with addClass() when you start loading, and remove it with removeClass in .load callback.

Upvotes: 0

DarkAjax
DarkAjax

Reputation: 16223

You can try something like this:

$(document).ready(function() {
    $(this).ajaxSend(function() {
        $(this).append('<div id="loading"></div>');
    }).ajaxStop(function() {
        $('#loading').remove();
    });
});

Which will work for all of your ajax calls...

Upvotes: 2

Mark Pieszak - Trilon.io
Mark Pieszak - Trilon.io

Reputation: 66911

Use the callback function of .load() to hide the loading div when it is finished.

function loadPage(){
    $('#loading').show();

    $("#content").load("example.html", function () { //calback function
         $('#loading').hide();
    });
}

Upvotes: 6

Related Questions