How To Use Callback Functions In JQuery With Example

admin_img Posted By Bajarangi soft , Posted On 13-10-2020

A callback function is executed after the current effect is 100% finished.So today we discuss how to do it

How To Use Callback Functions In JQuery With Example

JavaScript statements are executed line by line. However, with effects, the next line of code can be run even though the effect is not finished. This can create errors.

To prevent this, you can create a callback function.

A callback function is executed after the current effect is finished.

syntax: 

$(selector).hide(speed,callback);

The example below has a callback parameter that is a function that will be executed after the hide effect is completed:

Example For CallBack Functions

<script>
    $("button").click(function(){
        $("p").hide("slow", function(){
            alert("The paragraph is now hidden");
        });
    });
</script>


Example For WithOut CallBack Functions

<script>
 
    $("button").click(function(){
        $("p").hide(1000);
        alert("The paragraph is now hidden");
    });

</script>


Complete Code For Callback Functions In JQuery

<!DOCTYPE html>
<html>
<head>
    <title>How To Use Callback Functions In JQuery With Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<style>
    body {
        background: darkolivegreen;
    }
    .well{
        height:210px;

    }
</style>
<body>
<div class="container">
    <br><br><br>
    <div class="text-center">
        <h2 id="color" style="color: White">Callback Functions In JQuery </h2>
    </div>
    <br>
    <br>

    <div class="well">
        <button class="btn-success" id="Cf">CallBack Function</button>
        <button class="btn-success" id="Wcf">Without CallBack Function</button>
        <p class="p1">This is a paragraph with little content.</p>
        <p class="p2">This is a paragraph with little content.</p>
    </div>

</div>
</body>
</html>
<script>
    $(document).ready(function(){
        $("#Cf").click(function(){
            $(".p1").hide("slow", function(){
                alert("The paragraph is now hidden");
            });
        });
        $("#Wcf").click(function(){
            $(".p2").hide(1000);
            alert("The paragraph is now hidden");
        });
    });
</script>

 

Related Post