2080 7

CSC329 ยท 2080 ยท 5 marks

What is chaining in jQuery? Write a script to illustrate concept of chaining using slideUp and slideDown method.

What is chaining in jQuery? Write a script to illustrate concept of chaining using slideUp and slideDown method. [5]

Web TechnologyChapter 4: Client Side Scripting with JavaScriptEvents and Effects

Quick answer

Chaining allows us to run multiple jQuery commands, one after another, on the same element(s) in a single statement. To chain an action, we simply append the action to the previous action using the dot (.) operator. This makes the code shorter, cleaner, and more efficient because jQuery does not need to find the same element multiple times.

Chaining in jQuery

Definition

General Syntax:

$(selector).method1().method2().method3();

Script Illustrating Chaining using slideUp() and slideDown()

<!DOCTYPE html>
<html>
<head>
    <title>jQuery Chaining Example</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <style>
        #myDiv {
            width: 200px;
            height: 100px;
            background-color: lightblue;
            padding: 10px;
            font-size: 18px;
        }
    </style>
</head>
<body>

    <h2>jQuery Chaining Demo</h2>

    <div id="myDiv">This is a div element.</div>
     
    <button id="btn">Click to Chain Effects</button>

    <script>
        $(document).ready(function() {
            $("#btn").click(function() {
                $("#myDiv")
                    .css("color", "red")
                    .slideUp(1000)
                    .slideDown(1000);
            });
        });
    </script>

</body>
</html>

Explanation of the Script

StepCodeDescription
1.css("color", "red")Changes the text color of #myDiv to red
2.slideUp(1000)Slides the #myDiv element up (hides it) over 1000 milliseconds
3.slideDown(1000)Slides the #myDiv element down (shows it) over 1000 milliseconds

All three methods are chained together on the same element (#myDiv) in a single statement. jQuery executes them one after another in sequence.


Key Benefit

Without chaining, the same code would require three separate lines each finding #myDiv:

// Without chaining (less efficient)
$("#myDiv").css("color", "red");
$("#myDiv").slideUp(1000);
$("#myDiv").slideDown(1000);

With chaining, it is written in one clean statement, which is more readable and performs better.

Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.