What Is Meant By Method Chaining In JQuery With Example

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

In JQuery Chaining allows us to run multiple jQuery methods (on the same element) within a single statement.So today we discuss about it

What Is Meant By Method Chaining In JQuery With Example

Until now we have been writing jQuery statements one at a time (one after the other).

However, there is a technique called chaining, that allows us to run multiple jQuery commands, one after the other, on the same element(s).

To chain an action, you simply append the action to the previous action.

The following example chains together the css()slideUp(), and slideDown() methods. The "p1" element first changes to red, then it slides up, and then it slides down:

Step 1:Create index.html file and implement below code.

<p id="p1">jQuery is fun!!</p><br><br>
<p id="p2">jQuery is fun!!</p><br><br>
<button class="btn-success" id="Hide1">Hide1</button>
<button class="btn-success" id="Hide2">Hide2</button>
 

Step 2:Implement jquery to chain between slideup and slidedown.

<script>
    $(document).ready(function(){
        $("#Hide1").click(function(){
            $("#p1").css("color", "red").slideUp(2000).slideDown(2000);
        });
        $("#Hide2").click(function(){
            $("#p2").css("color", "red").slideUp(2000).slideDown(2000);
        });
    });
</script>


Complete Code For Method chaining In JQuery
<!DOCTYPE html>
<html>
<head>
    <title>What Is Meant By Method Chaining 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">Method Chaining In JQuery </h2>
    </div>
    <br>
    <br>

    <div class="well">
        <p id="p1">jQuery is fun!!</p><br><br>
        <p id="p2">jQuery is fun!!</p><br><br>
        <button class="btn-success" id="Hide1">Hide1</button>
        <button class="btn-success" id="Hide2">Hide2</button>

    </div>

</div>
</body>
</html>
<script>
    $(document).ready(function(){
        $("#Hide1").click(function(){
            $("#p1").css("color", "red").slideUp(2000).slideDown(2000);
        });
        $("#Hide2").click(function(){
            $("#p2").css("color", "red").slideUp(2000).slideDown(2000);
        });
    });
</script>

 

Related Post