views:

575

answers:

5

I want to show a div with a loading animation over my page while the page loads some XML content. Once its loaded, I want to hide this div. How can I go about doing this?

+8  A: 
$.ajax({
    url: '/test.xml',
    beforeSend: function(XMLHttpRequest) {
        // Show the div before sending the request
        $('#load').show();
    },
    complete: function(XMLHttpRequest, textStatus) {
        // Hide the div no matter if the call succeeded or not
        $('#load').hide();
    },
    success: function(xml) {
        // if the request succeeds do something with the received XML           
    }
});
Darin Dimitrov
+3  A: 
$.ajax({
    type: "GET",
    url: "your.xml",
    dataType: "xml",
    beforeSend: function() {
        $('#div').fadeIn();
    },
    success: function(xml) {
       // example for parsing xml
       $(xml).find('YOUR_XML_TAG').each(function(){
           // append xml to page HERE
       });
    },
    complete: function() {
       $('#div').fadeOut();
    }
});
cballou
+2  A: 

@cballou Your code will leave '#div' "up", if $.ajax() has not suceeded for any of numerous possible reasons.

DBJDBJ
noted and fixed.
cballou
A: 

I would use the onbeforeunload event fired when the page URL changes, to create an overlay div with opacity at 0.5, which will be replaced by the new content when the page is loaded.

Fabien Ménager
A: 

Almost right ;) Never under-estimate the importance of removing redundant $() calls. So ...

//all of this is inside some closure or function
var $blanket = $("#div") ; 
// check if after last call, something has possibly removed your '#div'
// throw if false
ASSERT( $blanket.length === 1 ) ;    
$.ajax({
        type: "GET",
        url: "your.xml",
        dataType: "xml",
        beforeSend: function() {  $blanket.fadeIn();
        },
        success: function(xml) {
           // example for parsing xml
           $(xml).find('YOUR_XML_TAG').each(function(){
               // append xml to page HERE
           });
        },
        complete: function() { $blanket.fadeOut();
        }
    });

--DBJ

DBJDBJ