
Callback in Jquery
? What is a Callback in jQuery?
A callback is a function that runs after another function finishes � it's commonly used in animations, AJAX, or events to make sure something happens in order.
? This is especially useful when you want to run code after an animation or effect finishes.
? Basic Syntax
$(selector).<div "#fadeBtn").click(function() { $("#box").fadeOut(1000, function() { alert("Fade out complete!"); }); });</script>
? The alert()
runs after the fade out completes.
? Example 2: Chaining with Callback
$("#box").slideUp(1000, function() { $("#box").slideDown(1000);});
? This smoothly slides the box up, then down � in perfect sequence.
? Example 3: Custom Callback Function
You can also define your callback function separately:
function showMessage() { console.log("Animation done!");}$("#box").animate({ width: "300px" }, 800, showMessage);
?? Why Use Callbacks?
Ensures order of execution
Prevents unexpected behavior in animations or AJAX
Makes your code cleaner and easier to manage
? Other jQuery Methods That Support Callbacks
Method | Callback Parameter? |
---|---|
.hide() | ? |
.show() | ? |
.fadeIn() | ? |
.fadeOut() | ? |
.slideUp() | ? |
.slideDown() | ? |
.animate() | ? |
? Summary
? A callback is a function that runs after another finishes
? Useful in animations, effects, AJAX, etc.
? Keeps your code clean and sequential