Reputation: 87
I have a snip of code that inst working the way it is supposed to.
function showContent(pos,direction){
$("#area").hide("slide", { direction: direction=="left"?"right":"left"}, 2000);
$("#area").load("flow_forms.jsp #area" + pos);
$("#area").show("slide", { direction: direction }, 500);
}
$('#next').click(function(){
if(question_pos==0){
question_pos+=1;
showContent(question_pos,"right");
return true;
The area is supposed to slide to the left, load off-screen, then slide in from the right with the loaded area contents.
Basically the problem I am having is that the .load is occurring before the .hide. So what I have is an area that loads as it slides to the left, then brings in the already loaded area in from the right. My boss suggested a callback function, but I don't even know what that is...
Upvotes: 1
Views: 433
Reputation: 15616
You should make use of callback functions - these are run once the current function has finished executing, like so:
function showContent(pos,direction){
$("#area").hide("slide", { direction: direction=="left"?"right":"left"}, 2000,
function(){
$("#area").load("flow_forms.jsp #area" + pos, function(){
$("#area").show("slide", { direction: direction }, 500);
}); // Load callback
} // Hide callback
);
}
Upvotes: 0
Reputation: 340055
You can make the .load
wait until the first animation has completed, either by using a completion callback, or by taking a "promise" on the element's animation queue:
$("#area").hide(...).promise().done(function() {
$("#area").load(..., function() {
$(this).show(...);
});
});
There's actually a better option, though, which would allow you to start the .load
while the animation is ongoing - this would be more responsive:
var $tmp = $('div');
var loaded = $.Deferred(function() {
$tmp.load(...); // load into an off-screen div
this.resolve();
});
var hidden = $('#area').hide(...).promise();
$.when(loaded, hidden).done(function() {
// move #tmp contents to #area and show it
$('#area').empty().append($tmp).show();
});
The $.when()
requires that both the AJAX load and the animation have completed, whilst allowing them both to progress at the same time.
Upvotes: 1