jQuery Callback

jQuery Callback Functions

JavaScript statements are executed line by line. However, with effects, the next line of code can be run even though the effect is not finished. This can create errors. To prevent this, you can create a callback function. A callback function is executed after the current effect is finished.

Syntax

$(selector).hide(speed, callback);

Why use jQuery Callback?

The example below has no callback parameter, and the alert box will be displayed before the hide effect is completed

Example

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").hide(1000);
alert("The paragraph is now hidden");
});
});
</script>
</head>
<body>
<button>Hide</button>
<p>This is a paragraph to be hide.</p>
</body>
</html>

Now run the code and click on the hide button before hidding the paragraph it will show the alert box.

jquery Callback method

jQuery Callback Method

The example below has a callback parameter that is a function that will be executed after the hide effect is completed.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").hide(1000, function(){
alert("The paragraph is now hidden");
});
});
});
</script>
</head>
<body>

<button>Hide</button>
<p>This is a paragraph to be hide.</p>
</body>
</html>

Output

jquery Callback method
Prev Next