Delay loading of ajax content with jQuery

I needed a function that would take the input of a form, show a loading graphic for a few seconds, and then load some content from an ajax page with jQuery load().

The loading is easy, but i had to experiment a little to get the right syntax for the 'wait a few seconds' part.

Here's what i came up with... this is all part of a function that runs 'onclick' from a link.

var loadingGraphic = '<img src="loading.gif">';
var gameContent = 'ajaxpage.cfm';

$('#gameSpace').html(loadingGraphic);

setTimeout(function(){
  $('#gameSpace').load(gameContent);
},2000);


this puts the loading graphic in place immediately with html(), and then waits 2 seconds before running the load() function to replace the contents via ajax. 

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
I came up with the following to do something similar (uses jQuery)

// submit filters form via ajax
$('#frmFilters input:checkbox').click(function(){
   
   // show ajax loader image
   var loader = '<img src="/
img/ajax_loader.gif" width="260" height="148" />';
   $('#productResults').html(loader);
   
   // serialize form data to pass via ajax
   var dataString = $('#frmFilters').serialize();

// fire ajax form submit
   $.ajax({
      type: "GET",
      url: "plp-getresults.php",
      data: dataString,
      success: function(msg){
         //alert( msg );
         $.doTimeout(500, function(){
            $('#productResults').html(msg);
         });
      }
   });   
});
# Author Dave Buchholz | 9/14/11 4:37 PM
1 liner:

$('#gameSpace').html('<img src="loading.gif">').delay(2000).queue(function() { $(this).load('ajaxpage.cfm'); });
# Author Tony Nelson | 9/14/11 4:57 PM
good options guys. always more than one way!

@tony: i totally forgot about queue() - no doubt the simplest. (I tried delay() on its own but that's only for events, didn't delay the load())

thanks!
# Author Michael Evangelista | 9/14/11 7:18 PM
blogcfc 5.9.1.002 by raymond camden
contact michael evangelista