Course Content
AJAX and jQuery Plugins
Learn how to use AJAX and plugins with jQuery to create dynamic and interactive web applications.
0/3
JQuery
About Lesson

Chaining in JQuery

jQuery chaining allows you to execute multiple actions on the same element in a single, concise statement. This improves code readability and efficiency.

Chaining in jQuery combines multiple method calls into one line, applied sequentially to the same element.

Syntax:

$(selector).action1().action2().action3();
  • Each method is executed in the order it is chained.

Example:

JavaScript
$("#box").slideUp(500).slideDown(500).fadeOut(500);
  • slideUp(500): Slides the element up in 500ms.
  • slideDown(500): Slides the element down in 500ms.
  • fadeOut(500): Fades the element out in 500ms

Practical Example:

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Chaining in jQuery</title>
  <style>
    #box {
      width: 100px;
      height: 100px;
      background-color: lightcoral;
      margin: 20px auto;
      border: 2px solid darkred;
    }

    #chain-action {
      display: block;
      margin: 10px auto;
      padding: 10px 20px;
      background-color: darkred;
      color: white;
      border: none;
      cursor: pointer;
    }
  </style>
</head>
<body>
  <button id="chain-action">Perform Actions</button>
  <div id="box"></div>

  <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
  <script>
    $(document).ready(function () {
      $("#chain-action").click(function () {
        $("#box").slideUp(500).slideDown(500).fadeOut(500);
      });
    });
  </script>
</body>
</html>
    1. Element Selection:
      • The #box is targeted for multiple actions.
    2. Chained Actions:
      • slideUp(500): Hides the box with a sliding-up effect in 500ms.
      • slideDown(500): Reveals the box with a sliding-down effect in 500ms.
      • fadeOut(500): Fades the box out in 500ms.
    3. Event Listener:
      • The chaining starts when the button with ID chain-action is clicked.

    Benefits of Chaining

    • Chaining: A powerful feature to execute multiple jQuery methods in a sequence.
    • Improves code efficiency and readability.
    • Perfect for combining animations, effects, and DOM manipulations.