Thursday 24 February 2011

Drupal 6 - Webforms: Loading GIF on Submit

If you have a slow mail server, then submitting webforms can sometimes appear to do nothing for a while. For me, this is anywhere between 2 and 8 seconds, but I have read about a lot of other people in similar situations. While the problem is with the mail server, sometimes there's nothing that can be done about this, and a simple solution to keep the user calm is to add a little loading animation. No Ajax involved: the GIF is simply shown when the user clicks submit, and then after the wait, they will be taken to the success page.

1) Grab the right GIF animation from this amazing site: http://ajaxload.info/ and put it here: /sites/all/images/loading.gif

2) The CSS: make it so that the GIF is used when a certain class is applied to an input element
input.form-submit.loading-gif {
 background: url('/sites/all/images/loading.gif') 50% 1px no-repeat;
}

3) The jQuery script: in your theme dir, create js/submit-loading.js which will apply the CSS class to the submit button when it is clicked
$(document).ready(function()
{
    // preload image
    (new Image()).src = "/sites/all/images/loading.gif";
    
    $(".webform-client-form").submit(function() {
        // select the button
        var $button = $(this).find("#edit-submit");
        // remove the text, but persist the width of the button
        var $buttonWidth = $button.outerWidth();
        $button.attr('value', '').width($buttonWidth);
        // display the loading gif and disable the button
        $button.addClass("loading-gif").attr('disabled','disabled');
    });
});

4) Add the script only to the right page with a bit of PHP in your theme's template.php. See #2 in my article: Different ways of adding JavaScript to a page

1 comment:

  1. Hi Jack

    Thanks for your tutorial, unfortunately when I added this script, it caused my forms not to submit - it would just reload the form and the submission wouldnt happen - nor would the loading.gif show up either.

    In an ideal world, what I was really looking for was some sort of lightbox popup with a loading indicator and some custom text - I have used Drupal webform in making an online assessment and it can take up to 10 seconds for drupal to build the results page with all of the calculations etc.

    If you have any ideas on how I would go about doing this, would be much appreicated.

    Thanks
    Jeremy

    ReplyDelete