views:

15902

answers:

4

When I submit a form using jQuery, I want to display an animation image (load.gif or progressbar.gif, etc.) for a few seconds.

How can I show a GIF image in jQuery?

+6  A: 

Perhaps you should look into the Throbber plugin for jQuery.

(As a side note, I still can't believe that loading animations are called "throbbers".)

Daniel Lew
+1 for the giggles wrt 'throbber'.
Travis
+30  A: 

As far as the actual loading image, check out this site for a bunch of options.

As far as displaying a DIV with this image when a request begins, you have a few choices:

A) Manually show and hide the image:

$('#form').submit(function() {
    $('#wait').show();
    $.post('/whatever.php', function() {
        $('#wait').hide();
    });
    return false;
});

B) Use ajaxStart and ajaxComplete:

$('#wait').ajaxStart(function() {
    $(this).show();
}).ajaxComplete(function() {
    $(this).hide();
});

Using this the element will show/hide for any request. Could be good or bad, depending on the need.

C) Use individual callbacks for a particular request:

$('#form').submit(function() {
    $.ajax({
        url: '/whatever.php',
        beforeSend: function() { $('#wait').show(); },
        complete: function() { $('#wait').hide(); }
    });
    return false;
});
Paolo Bergantino
Oh, and +1 for providing an answer. Only improvement would have been to mention 'throbbers' :-).
Travis
+2  A: 

This would make the buttons disappear, then an animation of "loading" would appear in their place and finally just display a success message.

$(function(){
    $('#submit').click(function(){
     $('#submit').hide();
     $("#form .buttons").append('<img src="assets/img/loading.gif" alt="Loading..." id="loading" />');
     $.post("sendmail.php",
       {emailFrom: nameVal, subject: subjectVal, message: messageVal},
       function(data){
        jQuery("#form").slideUp("normal", function() {       
         $("#form").before('<h1>Success</h1><p>Your email was sent.</p>');           
        });
       }
     );
    });
});
Luis Armando
A: 

http://plugins.jquery.com/project/loading

lots of options and animations, super easy to use. check out the demo page.

Nathan Bubna