Home    Articles

 

How to create loading overlay over div for ajax call

 

We often want to create an overlay over some div or entire html body when a new form is submited or a new search filter is applied. Here is how it can be done as simple as posible.

Step 1:

Add this class to your css with your loading image, it must be gif (see path: "images/loading.gif" )

.loadingOverlay {
    display:    none;
    position:   fixed;
    z-index:    1000;
    top:        0;
    left:       0;
    height:     100%;
    width:      100%;
    background: rgba( 255, 255, 255, .8 ) 
                url('images/loading.gif') 
                50% 50% 
                no-repeat;
}

Step 2:

Add this div into your html code exactly where you need it: 

<div class="loadingOverlay"></div>

Step 3:

Use this class in your ajax call: 

$( document ).on('click','#element_id',function() {
			$('.loadingOverlay').show();  //show the overlay when ajax call is made
		
			$.ajax({
		        url:  'your request link here',
		        type: 'POST',
		        async: true,
		        data: { 
		        		item: value,
		        	  },
		        error: function(){
		            return true;
		        },
		        success: function(response) { 
					$('.do_something_with_response').hide().html(response).fadeIn(700, function() {});
					$('.loadingOverlay').hide(); // hide the overlay when ajax call is done
		        }
		  });
	});

This works very simple: You create a simple div with a class associated. This div is hidden until the ajax call has started, then the div is displayed and it will look as an overlay. When the ajax call has finished you can hide it. 

It is very important that your ajax call to be "async:true" in order to see the overlay.

Enjoy.

by