Showing the loading icon when jQuery is waiting for a response

Here’s a very simple method of putting an overlay on the page when you are making an asynchronous call using $.ajax. As the page does not refresh, you need to alert your user that work is actually been done and that they cannot interact with the page until you have finished

The css:

.lightbox_bg {
        background:#ffffff none repeat scroll 0 0;
        display:none;
        height:800px;
        left:0;
        filter:alpha(opacity=50);
        opacity: 0.5;
        top:0;
        width:100%;
        z-index:1110;
        display:none;
        position:fixed;
    }
    .modal{
        position:absolute;
        left:45%;
        top:45%;
        z-index:1111;
        width:32px;
        height:32px;
        background:url(/image/of/your/choice.gif) #fff 50% 50% no-repeat;}

The javascript:

$(‘body’).ajaxStart(function() {
        $(‘<div />’).addClass(‘lightbox_bg’).appendTo(‘body’).show();
        $(‘<div />’).addClass(‘modal’).appendTo(‘body’);
    });
    $(‘body’).ajaxStop(function() {
        $(‘.lightbox_bg’).remove();
        $(‘.modal’).remove();
    });

Thats it, now everytime you do your ajax magic the ajaxstart method will kick in and do its bit – then when its finished the ajaxstop method will remove the overlay.

You can follow any responses to this entry through the RSS 2.0 feed.