Callbacks - Doing Something When an Effect is Done

Contact Us or call 1-877-932-8228
Callbacks - Doing Something When an Effect is Done

Callbacks - Doing Something When an Effect is Done

Often, you'll want to run some code once an animation is done -- if you run it before the animation is done, it may affect the quality of the animation, or it may remove elements that are part of the animation. Callback functions provide a way to register your interest in an event that will happen in the future. In this case, the event we'll be responding to is the conclusion of the animation. Inside of the callback function, the keyword this refers to the element that the effect was called on; as we did inside of event handler functions, we can turn it into a jQuery object via $(this).

A callback will be invoked once for each element that the query retrieves.

Running Code When an Effect is Complete

$('div.old').fadeOut(300, function() { $(this).remove(); });

Note that if your selection doesn't return any elements, your callback will never run! You can solve this problem by testing whether your selection returned any elements; if not, you can just run the callback immediately.

Run a Callback Even if There Were No Elements to Animate

var $thing = $('#nonexistent');

var cb = function() {
	console.log('done!');
};

if ($thing.length) {
	$thing.fadeIn(300, cb);
} else {
	cb();
}
Next