Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Use of Callback Functions in jQuery

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 163
    Comment on it

    We well know that  JavaScript code is run line by line but in some cases, the next line of code can be executed before completion of the previous line of code and this cause that its give unexpected result or errors. To fix this type of problem in jQuery, we can create callback methods.

    A callback function is called after the 100% completion of the current process.

    A callback method is always called by other method.

     

    Example with callback function:

    $(document).ready(function(){
        $("#btn_id").click(function(){
            $("p").fadeOut("slow", function(){
                alert("The paragraph is now hidden");
            });
        });
    });

     

    The above example has a callback argument i.e. a function that will be called after the 100% completion of the fadeOut process.

     

    Example without callback function:

    $("#btn_id").click(function(){
     $("div").hide(900);
     alert("Before completion of hide() it will run alert!!");
    });

     

    The above example has  no callback function that why its run alert pop-up without completion of hide() function.

     

    <!DOCTYPE html>
    <html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
        $("#btn_id").click(function(){
            $("p").fadeOut("slow", function(){
                alert("The paragraph is now hidden");
            });
        });
    
        $("#btn_id_callback").click(function(){
     $("div").hide(900);
     alert("Before completion of hide() it will run alert!!");
    });
    });
    </script>
    </head>
    <body>
    
    <button id="btn_id">Example with callback</button> <button id="btn_id_callback">Example withOut callback</button>
    
    <div>A callback function is called after the 100% completion of current process.</div>
    
    </body>
    </html>

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: