Currently I'm hiding a div with id "countries" slowly and in it's complete function I'm making an ajax call in which in it's done function I get a partial view and replace the div with the result and then show() again slowly.
This waits until the hide animation is complete before it makes the ajax call. To make this more efficient and to use the time it takes to hide the div efficiently is there a way that I can make the ajax call before I hide, and only show again once both the ajax is done AND the hide animation is complete?
Sometimes the hide isn't finished before the ajax is done and it doesn't make a smooth transition and if I place the ajax call inside the hide complete animation function there can be a delay that isn't so smooth.
So the smoothest possible transition is make the ajax call right away, but only reshow the div when the hide animation is complete. How could I do that?
Below is what I have now but it waits until the hide animation is complete before making the ajax call which isn't the most efficient to make a smooth experience.
$("#countries").hide("slow", function(){
$.ajax({
url: 'blah',
type: 'get',
data: { region: region }
})
.done(function(result){
$("#divCountries").html(result);
$("#countries").show("slow");
});
});
I posted a revised answer that uses $.when. For history sake, I'm not going to change this code.
Try your URL with the following. If you have a problem let me know in a comment. This is how it works for me:
Some HTML
<div style="background-color: red;" id="countries">countries div</div>
<button id="get">Get</button>
Some Javascript
var hidden = false;
var ajax = false;
$(document).ready(function() {
$('#get').click(function() {
$("#countries").hide("slow", function() {
$.ajax({
url: 'blah',
type: 'get',
data: { region: region },
success: setAjaxFlag(),
error: setAjaxFlag()
}).done(function(){
setHiddenFlag();
showCountries();
});
})
});
});
function setAjaxFlag() {
ajax = true;
}
function setHiddenFlag() {
hidden = true;
}
function showCountries() {
if(ajax === true && hidden === true) {
$("#divCountries").html(result);
$("#countries").show("slow");
} else {
showCountries();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With