Sometimes it is crticial that you know when the effect completes.
For example if you fade in an image, you may not want the caption to show until the fade in is complete.
For this, you use a
callback function. A callback
function is called when the effect is competed. An anonymous function
which serves as the callback function is passed as the second argument
for most effects (after the length) and for others like animate() that
take more then one argument, the callback function is passed as the
last argument.
[
jq_04_callback.html]
//caption fades in after fade in for div is complete
$(document).ready(function(){
$('div').hide();
$('.caption').hide();
$('button').click(function(){
$('div').fadeIn(2000, function(){$('.caption').fadeIn(500);} );
});
});
The lab assignment from last class uses this callback function as well...
[
jq_03_scroll.v3.html]
An example of a callback function called from a callback function... [
jq_04_callback_v2.html]
$(document).ready(function(){
$('div').hide();
$('.caption').hide();
$('button').click(function(){
$('div').fadeIn(2000,
function(){$('.caption').fadeIn(500,
function(){$('div').fadeOut(3000);
$('.caption').fadeOut(3000);
});
});
});
});
If you want to animate one element, a sequential listing of events would do.
[
jq_04_callback_v3.html]
$(document).ready(function(){
$('div').hide();
$('button').click(function(){
$('div').fadeIn(1000);
$('div').fadeOut(1000);
});
});
Finally, if you want to wait a certain time for an effect to take play, use the delay() function.
[
jq_04_callback_v4.html]
$(document).ready(function(){
$('div').hide();
$('button').click(function(){
$('div').fadeIn(1000).delay(2000).fadeOut(1000);
});
});