jQuery Callbacks is a key concept that helps you run code after an animation or effect finishes.
What is a jQuery Callback?
A callback is a function that is executed after the current effect is complete .
In jQuery, many effects like .hide() , .show() , .slideDown() , .fadeOut() , .animate() , etc. allow you to pass a callback function as the last parameter .
Syntax:
$(selector).effect(duration, callback);
Or simply:
$(selector).effect(callback);
The example below has a callback parameter that is a function that will be executed after the hide effect is completed:
Example
< script >
$ (document).ready(function (){
$ ("#hideBtn" ).click(function (){
$ ("#box" ).hide(1000 , function (){
alert("Box is now hidden!" );
});
});
});
</script >
show = true, 3000)" class="absolute top-[10px] right-[10px] inline-flex items-center justify-center gap-2 text-sm font-medium hover:bg-accent hover:text-accent-foreground transition-smooth h-9 rounded-md px-3 cursor-pointer bg-white/80 border border-border">
Try it yourself
The example below has no callback parameter, and the alert box will be displayed before the hide effect is completed:
Example
<script >
$ (document).ready(function (){
$ ("button" ).click(function (){
$ ("p" ).hide(1000 );
alert("The paragraph is now hidden" );
});
});
</ script >
show = true, 3000)" class="absolute top-[10px] right-[10px] inline-flex items-center justify-center gap-2 text-sm font-medium hover:bg-accent hover:text-accent-foreground transition-smooth h-9 rounded-md px-3 cursor-pointer bg-white/80 border border-border">
Try it yourself