jQuery Callback Functions
What is a Callback Function?
A callback function is a function that executes after another function has completed.
Since jQuery animations and effects run asynchronously, a callback function ensures that code executes in the correct order.
Why Use Callback Functions?
✅ Ensures proper execution order – Prevents animations from running at the same time.
✅ Used after effects (hide(), fadeOut(), slideUp(), etc.) – Runs code only after the effect is finished.
✅ Improves user experience – Avoids unexpected behavior.
How to Use Callback Functions in jQuery?
Syntax:
$(selector).effect(speed, function() {
// Code to run after the effect completes
});
• effect – Any jQuery effect method (hide(), fadeOut(), slideUp(), etc.).
• speed – Optional (“slow”, “fast”, or milliseconds like 1000).
• function() – The callback function that runs after the effect completes.
Examples of jQuery Callback Functions
1. Running Code After an Animation Ends
👉 Example: Hide a paragraph and then show an alert.
$(“#hideBtn”).click(function() {
$(“p”).hide(“slow”, function() {
alert(“Paragraph is now hidden!”);
});
});
📌 What happens?
• The paragraph hides slowly.
• After it is hidden, an alert pops up saying “Paragraph is now hidden!”.
2. Callback After fadeOut()
👉 Example: Fade out a paragraph and then change its text.
$(“#fadeOutBtn”).click(function() {
$(“p”).fadeOut(“slow”, function() {
$(this).text(“This text has changed after fadeOut!”).fadeIn(“slow”);
});
});
📌 What happens?
• The paragraph fades out slowly.
• After it disappears, the text changes.
• The new text then fades in slowly.
3. Callback After slideUp()
👉 Example: Slide up a div and then show a message.
$(“#slideUpBtn”).click(function() {
$(“#box”).slideUp(1000, function() {
alert(“The box is now hidden!”);
});
});
📌 What happens?
• The #box slides up in 1 second.
• After it disappears, an alert appears saying The box is now hidden!
4. Stacking Multiple Animations Using Callbacks
👉 Example: Chain animations using callbacks.
$(“#animateBtn”).click(function() {
$(“#box”).animate({ width: “300px” }, 1000, function() {
$(this).animate({ height: “200px” }, 1000, function() {
$(this).css(“background-color”, “red”);
});
});
});
📌 What happens?
• The #box expands horizontally.
• Then, it expands vertically.
• Finally, it turns red.
Conclusion
🎯 Callback functions ensure one function runs after another finishes.
🎯 Useful for animations and effects like hide(), fadeOut(), slideUp(), etc.
🎯 Helps in creating smooth, step-by-step animations.