Animation Callback Functions
In this page:
Completion Callback
A completion callback is a function passed as the last argument to an effect method, and jQuery runs it only after that specific animation finishes.
Example: Completion Callback
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="box">Box</div>
<script>
$("#box").fadeOut(1000, function() {
console.log("Fade complete");
});
</script>
</body>
</html>
animate() Callback
animate() accepts a callback as its final argument just like the simpler effect methods do, running it once the property transitions it's controlling have all completed.
Example: animate() Callback
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="box" style="width:100px">Box</div>
<script>
$("#box").animate({width: "300px"}, function() {
console.log("Animation complete");
});
</script>
</body>
</html>
Run Another Action
Callbacks are the standard way to chain behavior onto the end of an animation -- for example removing an element from the DOM only after it has finished fading out, rather than removing it immediately and cutting the animation short.
Example: Run Another Action
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="box">Box</div>
<script>
$("#box").fadeOut(1000, function() {
$(this).remove();
});
</script>
</body>
</html>
Callback this
Inside a jQuery animation callback, the keyword this refers to the raw DOM element that was animated, not a jQuery object, so it typically needs to be wrapped in $(this) before calling other jQuery methods on it.
Example: Callback this
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="box" data-name="mybox">Box</div>
<script>
$("#box").fadeOut(1000, function() {
console.log($(this).data("name"));
});
</script>
</body>
</html>
Callback and Queue
Starting a second animation from inside a completion callback lets you build multi-step sequences, like sliding an element up and then fading it out, without both effects running simultaneously.
Example: Callback and Queue
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="box">Box</div>
<script>
$("#box").slideUp(500, function() {
$(this).fadeOut(500);
});
</script>
</body>
</html>
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: