Description :
As we know javascript code run line by line and sometimes the current line effect is still in progress but the next line executes and this creates an error.
To prevent this, we can create callback functions.
In this example, we have used a callback parameter that is a function that will be executed and will be showing an alert message after the hide effect is completed.
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("h1").hide("slow", function(){ alert("wow that's hide it"); }); }); }); </script> </head> <body> <button>Hide Me!!</button> <h1 style="color:darkred">you can experiment your code online with Learnkode
Description :
In this example, we will place the slideToggle()
(Combination of slideUp()
and slideDown()
)and alert()
statements next to each other. If you try this code the alert will be displayed immediately once you click the trigger button without waiting for slide toggle effect to complete.
<!DOCTYPE html> <html> <head> <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> <style> p{ background:rgb(0, 234, 255); font-size: 30px; padding:20px; } </style> <script> $(document).ready(function(){ $("button").click(function(){ $("p").slideToggle("slow", function(){ alert("The slide toggle effect has completed."); }); }); }); </script> </head> <body> <h1>Click to Hide Text </h1> <p> APPWRK IT Solutions makes technology simple for you</p> <button type="button" style="height: 40px; width:150px">Click me to Hide/show</button> </body> </html>
Description :
A Callback() function is executed once the effect is complete. It is always written as the last argument of the method.
Syntax: $(selector).effect_function(speed, callback);
.In this example we are going to use callback function multiple time with the help of slidetToggle()
function
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> <style type="text/css"> h1{ display:none; background:cyan; padding:20px; } p{ background:maroon; font-size: 24px; padding:20px; } </style> <script> $(document).ready(function(){ $("button").click(function(){ $("h1, p").slideToggle("slow", () =>{ alert("The slide toggle effect has completed."); }); }); }); </script> </head> <body> <h1>Hello I am steve jobs</h1> <p style="color: mediumspringgreen">Co- founder of Iphone Company</p> <button type="button">Click me</button> </body> </html>