jQuery Callback Functions – Ensuring Code Runs at the Right Time
In JavaScript, code is executed line by line, even if an effect (like
hide() or fadeOut()) is still running. This can lead to unexpected behavior
when the next statement depends on the animation being finished.
To solve this, jQuery provides callback functions functions that are
executed only after an effect has completed.
Syntax:
$(selector).hide(speed, callback);
The callback parameter is a function that runs after the hide() effect is
fully completed.
Example With Callback:
In this example, the alert appears after the paragraph is completely
hidden:
<!DOCTYPE html>
<html>
<head>
<title>jQuery hide() Callback Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").hide("slow", function(){
alert("The paragraph is now hidden");
});
});
});
</script>
<style>
p {
padding: 10px;
background: #f4a261;
color: white;
border-radius: 6px;
}
button {
margin-top: 10px;
padding: 8px 16px;
font-size: 16px;
}
</style>
</head>
<body>
<h2>jQuery hide() with Callback Example</h2>
<p>This is a paragraph. Click the button to hide me.</p>
<button>Hide Paragraph</button>
</body>
</html>
Example Without Callback:
Here, the alert box shows up immediately, before the paragraph finishes
hiding:
<!DOCTYPE html>
<html>
<head>
<title>jQuery hide() Without Callback</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").hide(1000);
alert("The paragraph is now hidden"); // Runs immediately, not after
hide
});
});
</script>
<style>
p {
padding: 10px;
background: #2a9d8f;
color: white;
border-radius: 6px;
}
button {
margin-top: 10px;
padding: 8px 16px;
font-size: 16px;
}
</style>
</head>
<body>
<h2>jQuery hide() Without Callback</h2>
<p>This is a paragraph. Click the button to hide me.</p>
<button>Hide Paragraph</button>
</body>
</html>
Using callback functions helps maintain proper flow and ensures that
actions dependent on animations happen at the right time.
More topic in jQuery