JQuery Callback Functions :
Callback functions are the greatest addition in JQuery. We can pass the callback functions into every Jquery functions. The JQuery Call back functions are called by the JQuery it self when function execution is completed.
Line by line execution is performed in JavaScript. But in jQuery, sometimes skips the code to next line without executing the previous line. The jQuery Callback Functions are used to prevent this type of execution on jQuery.
Most of the time the effect method is to execute the functions before finishing the animation. So, in effects, the jQuery callback functions are passed as a parameter. This is the last parameter on the effect method. Once the effect is finished the callback function is executed.
[box type=”shadow” align=”alignleft” class=”” width=”100%”]
$(selector).fadeToggle(duration, callback);
[/box]
The parameter duration represents three speeds. They are fast, slow and normal. It runs in few milliseconds. The jQuery Callback Functions represents the execution of function after animation completes. It executes only once for each element on a web page.
Here is the example for JQuery Callback function :
[sourcecode language=”html”]
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JQuery Callback Functions Example</title>
<style type="text/css">
p {
font-size: 20px;
color: blue;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<button>FadeToggle</button>
<button>FadeToggle Callback</button>
<p>FadeToggle</p>
<p>FadeToggle Callback</p>
<div id="log"></div>
<script>
$("button:first").click(function() {
$("p:first").fadeToggle("slow", "linear");
});
$("button:last").click(function() {
$("p:last").fadeToggle("fast", function() {
alert("Action completed..")
});
});
</script>
</body>
</html>
[/sourcecode]
On the above example, we can get “Action completed..” Alert after fadeToggle() method executed successfully.
Happy Learning 🙂