tags:

views:

1397

answers:

5

hi im looking for any tutorials/articels about inserting a loading gif while elements load, ive seen it in a few sites. i can only seem to find articles on preloading images.

+1  A: 

A general strategy is to place the loading image in a div or span tag, and show or hide it when you want to show it. If you want to show it initially, just place a jQuery .hide() function on the div or span in the jQuery on ready function.

See the jQuery docs on show() and hide()

jonstjohn
or set the background image of the div to the "loading" image. Then you don't have to do anything (unless the browser draws a placeholder while loading)
Philippe Leybaert
+3  A: 

Depending on what you are trying to do, it's not particularly hard. The following will show a loading image (pre-existing), then load some html retrieved via ajax, then upon completion, it will hide the loading image.

$(function() {
   $('#activate').click( function() {
      $('#loadingImg').show();
      $('#whereItGoes').load( 'url-to-data-to-be-loaded', function() {
          $('#loadingImg').hide();
      });
   });
});

If the data to be loaded are images, then it gets a little tricker since the load callback may be called before the image data is actually downloaded. One strategy in that case is to have a script included with the HTML that knows how many images are to be loaded and have an onloaded event handler that basically ticks off the image count until all the images have been downloaded. I usually couple it with a timeout in case the onloaded handler doesn't get added before the image data is available (in which case it won't fire).

tvanfosson
+1  A: 

It's usually nothing more than:

function onAGivenEvent() {
    $('someContain').append('<div id="throbber"></div>');
    // do some slowthings with a "on complete callback to onComplete
}

function onComplete() {
    $('#throbber').remove();
}

But there are also cases where you don't even need Javascript. For example in case of large images. In that case you can do it using HTML and CSS:

img.largeImage {
   background: url(throbber.gif) center no-repeat;
}

and in HTML

<img class="largeImage" src="..." />
elmuerte
+1  A: 

You can generate the loader GIFs here: http://www.ajaxload.info/

Mat Ryer
A: 

I made a plugin to simplify all this. Here's the demo:

http://jquery-values.googlecode.com/svn/other/loading/jquery.loading.htm

Nathan Bubna