Did you find this useful?
Socialize it today.


jQuery Callback

Monday, July 09, 2012

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 chanages 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> 


slide toggle
Without callback. Note the toggle icon.


slide toggle
With callback. Note the toggle icon.


Please help us spread the word by socializing it today!

email contact us

Did you find something wrong with the information on this page? Please take a moment to report it to us so that we can continue to improve the quality of the information on this site. Click here to report an issue with this page.



Recommended Books & Training Resources

JavaScript and jQuery: The Missing Manual Professional jQuery Pro jQuery