jQuery Callback Functions


A callback function is executed, after the current effect or animation has completed completely.

You can execute codes before completting the effects or animation. But in many situations this can cause mistakes or invalid results.

You can build a callback function in order to prevent this problem.

When the current effect or animation is completed, a callback function is executed.

Typical syntax:

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

Note:- You can use any jquery effect methods insteadof hide()

Example:-

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
    $(document).ready(function () {
        $("#b1").click(function () {
            $("#p1").hide("slow");
            alert("The paragraph is now hidden");
        });

        $("#b2").click(function () {
            $("#p2").hide("slow", function () {
                alert("The paragraph is now hidden");
            });
        });
    });
</script>
</head>
<body>

<button id="b1">Without Callback</button><br /><br />

<p id="p1">This is a paragraph with little content.</p>

<button id="b2">With Callback</button><br /><br />

<p id="p2">This is a paragraph with little content.</p>

</body>
</html>

Output :-



This is a paragraph with little content.



This is a paragraph with little content.


Note:- After clicking "Without Callback" button, we will get an unexpected result. The popup message will show you before hiding the paragraph.

The "With Callback" button contains a callback parameter which is a function to be performed once the effect of a hide is finished.

You can also search for these topics, use of jquery callback function, parameters available, return the value of callback function, on click, execute after append, jquery and ajax callback function, jquery callback function after form submit, multiple functions works, jquery complete the callback function, syntax and example for jquery callback functions.