Normally, javascript codes are executed by line. But, jQuery effect takes few times to finish the next line code may execute when the previous effect is still running. To overcome this, jQuery contributes a callback function.

What is a Callback Function in jQuery?

A Callback function is nothing but a jQuery function, which will be executed once the effect is complete.

A callback function is called as a higher-order function that can be passed to another function as a parameter. That callback function will be executed inside the other function. Hence, the use of this callback function is known as the callback pattern. Moreover, it is always appears as the last argument of the method.

Syntax with Callback Function as a Parameter

Here is the basic syntax of the jQuery slideToggle() effect method with a callback function;

$(selector).slideToggle(duration, callback);
Example: 1
<head>

<title>Example of jQuery Effect Method with Callback Function</title>

<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>

<style type="text/css">

    p{

        background:yellow;

        font-size: 24px;

        padding:20px;

    }

</style>

<script type="text/javascript">

$(document).ready(function(){

    $("button").click(function(){

        $("p").slideToggle("slow", function(){

            alert("The slide toggle effect has completed.");

        });

    });  

});

</script>

</head>

<body>

    <p>This is paragraph.</p>

    <button type="button">Click me</button>

</body>

Basic Noteworthy Principles for Callback Function
Final Words

Once you are familiar and understand every nook and corner of a callback function, then you can start making your own callback functions. Because, callback functions are very simple yet powerful to use and they offer amazing features to your web applications and code.

Leave a Reply

Your email address will not be published. Required fields are marked *