Reputation: 239
I have a simple page where by clicking on button new data are loaded to DIV by ajax function. That DIV fades out when user click on another button, datas are loaded and the DIV fades IN again. the trouble is when user click on button DIV fades out but with new data already loaded.
I tried to use callback in FadeOut function to prevent new data loaded before fading out, but it didn't help. my code is as below:
effect of fading out with callback:
$("#core").fadeOut(500, processingPages.loadPage(clickedButton));
loadPage function:
loadPage: function(bottomMenu) {
$("#indicator").show();
$.ajax({url: bottomMenu.attr('href'),
dataType: 'html',
timeout: 5000, // 5 seconds
success: function(html) {
$("#indicator").hide();
$("#core").html(html).fadeIn(500);
}
}
What am I doing wrong? Why Fade out doesn't wait for 500ms and than run loadpage function. why is Ajax function triggered straight away?
Upvotes: 1
Views: 493
Reputation: 8699
Use promises. Keeps things really simple.
var fadingOut = $("#core").fadeOut(500).promise()
fadingOut.done(function() {
processingPages.loadPage(clickedButton)
});
Although this is a simple example, get in this habit and everything will be a lot easier for you.
You can even use promises with ajax, jquery ajax calls return promises by default. Your loadPage function could look something like this:
loadPage: function(bottomMenu) {
$("#indicator").show();
var gettingData = $.ajax({url: bottomMenu.attr('href'),
dataType: 'html',
timeout: 5000
});
gettingData.done(function(html) {
$("#indicator").hide();
$("#core").html(html).fadeIn(500);
});
gettingData.fail(function() {alert("There was a problem loading your data";});
}
Upvotes: 0
Reputation: 34556
$("#core").fadeOut(500, function() {
processingPages.loadPage(clickedButton));
});
This is a common mistake. You mean to pass a function, but you are in fact passing the return value of the function, because you are executing immediately rather than requesting that it execute at a later time.
In mine, I am passing an anonymous function (not a return value OF a function) which, when executed (i.e. after fade out) does your code.
It's the diference between function reference and function invocation.
alert //reference to alert function
alert('hello'); //invocation of alert function
Upvotes: 1
Reputation: 15338
try:
$("#core").fadeOut(500, function(){
processingPages.loadPage(clickedButton);
});
Upvotes: 1