jQuery .load when complete fade in and remove loading spinner
I am using jQuery .load function to get 3 list items from other page. It is working perfectly, but I was wo开发者_JAVA百科ndering how to add "loading spinner" while content is loading and how to fade in my content, when it is loaded.
My code :
$('.homeProducts').load('http://localhost/products #product_list li:lt(3)');
P.S I don't know it is the right way to get those products, but it works for me.
The best was is using the global ajaxStart
and ajaxStop
events:
$('#yourSpinner').ajaxStart(function() {
$(this).show();
}).ajaxStop(function() {
$(this).hide();
});
The ajaxStart
event will fire when the number of pending ajax requests raises from 0 to 1 and the ajaxStop
event will fire when all ajax requests have finished.
I usually do something like this:
$("#content").html('<div align="center"><img style="margin: 10px 0px 10px 0px;"
align="center" src="ajax-loader.gif"></div>');
setTimeout('do()', n);
...
function do(){
$("#content").load('http://localhost/products #product_list li:lt(3)',{},function(){
$(this).fadeIn();
});
}
Where n is the ammount of time after wich the function will be fired. So the spinner is shown for at least n milliseconds.
精彩评论