logo
jQuery Callback Functions
JavaScript statements are executed line by line. But, since jQuery effect takes some time to finish the next line code may execute while the previous effect is still running. To prevent this from happening jQuery provides a callback function for each effect method.

A callback function is a function is executed after the current effect is finished.

The callback function is passed as an argument to the effect methods and they typically appear as the last argument of the method. For example, the basic syntax of the jQuery slideToggle() effect method with a callback function  that will be executed after the hide effect is completed.
jQuery Callback Function
<!DOCTYPE html>
<html>
<head>
<title>jQuery Callback Functions</title>
 
<script src="js/jquery-3.2.1.min.js"></script>  
<script type="text/javascript">
$(document).ready(function(){
    $("button").click(function(){
        $("p").slideToggle("slow", function(){
            alert("The slide toggle effect has completed.");
        });
    });   
});
</script>
<style type="text/css">
.btn{ padding:6px 15px;}
    p{ background:#0099da; font-size: 24px;padding:20px; color:#FFF; text-align:center;}
</style>
</head>
 
<body>
 
<button type="button" class="btn">Click Here!</button>
    <p>This is a sample paragraph.</p>
    
</body>
</html>   
Output :
jQuery Without Callback Function
The below example has no callback parameter, and the alert box will be displayed before the slideToggle() effect is completed :
<!DOCTYPE html>
<html>
<head>
<title>jQuery Without Callback Functions</title>
 
<script src="js/jquery-3.2.1.min.js"></script>  
<script type="text/javascript">
$(document).ready(function(){
    $("button").click(function(){
//$("p").slideToggle(1000);
$("p").slideToggle("slow");
        alert("The slide toggle effect has completed.");
    });   
});
</script>
<style type="text/css">
.btn{ padding:6px 15px;}
    p{ background:#0099da; font-size: 24px;padding:20px; color:#FFF; text-align:center;}
</style>
</head>
 
<body>
 
<button type="button" class="btn">Click Here!</button>
    <p>This is a sample paragraph.</p>
    
</body>
</html> 
Output :