Computers & ProgrammingFrontend DevelopmentjQuery

jQuery Callback

The jQuery callback function solves a very common problem when dealing with animation. JavaScript statements are executed line by line. There are instances when working with animations, where you do not want the next line of code to be executed until the animation has been completed. To prevent this from happening, you can use the callback function.

Syntax

$(selector).effect(speed,callback)
ParameterDescription
callbackAn optional function to run after the method is completed

HTML Example

We will use the following HTML for the examples listed below.

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
          // ... jQuery Code ...
        });
    </script>
</head>
<body>
    <img id="img3" src="toggle.png" /> ; 
    <div id="div1"> <!-- Some Content --> </div>
</body>
</html>

Example

In the following examples, we will look at the difference between using the callback function and omitting the callback function. In the first example, no callback function is used. Notice that the toggle image changes before the animation is completed.

In the second example, the callback function is used and the toggle image is not modified until the animation is completed.

<script type="text/javascript">
    $(document).ready(function () {
        $("#img1").click(function () {
            $("#div1").slideToggle("slow");
            var $img = $("#img1");
            if ($img.attr("src") == "expand.png") {
                $img.attr("src", "collapse.png");
            } else {
                $img.attr("src", "expand.png");
            }
        });
        $("#img2").click(function () {
            $("#div2").slideToggle("slow", function () {
                var $img = $("#img2");
                if ($img.attr("src") == "expand.png") {
                    $img.attr("src", "collapse.png");
                } else {
                    $img.attr("src", "expand.png");
                }
            });
        });
    });
</script> 

Leave a Comment

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

Scroll to Top