How to Create a Slide Up Animation in jQuery

The jQuery method used to create a sliding up animation is slideUp(). This article provides a concise overview of how slideUp() works, its syntax, available parameters, and a practical code example to help you implement smooth vertical hiding effects on web page elements.

The slideUp() Method

The slideUp() method animates the height of matching elements, gradually decreasing their height until they are completely hidden from view. Once the animation finishes, jQuery automatically sets the CSS display property of the element to none.

Syntax

$(selector).slideUp(speed, easing, callback);

Parameters

All parameters for slideUp() are optional:

  • speed (or duration): Specifies the duration of the effect. It can be defined in milliseconds (e.g., 400, 1000) or using predefined strings such as "slow" (600ms) or "fast" (200ms). The default value is 400 milliseconds.
  • easing: Determines the speed of the animation at different points. Standard jQuery includes "swing" (the default, which speeds up in the middle and slows down at the ends) and "linear" (a constant speed throughout).
  • callback (or complete): A function to execute once the sliding animation has fully completed.

Practical Example

Here is a basic implementation of slideUp() triggered by a button click:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>jQuery slideUp Demo</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <style>
    #panel {
      padding: 20px;
      background-color: #e0e0e0;
      border: 1px solid #ccc;
    }
  </style>
</head>
<body>

  <button id="hideBtn">Slide Up</button>
  <div id="panel">This content will slide up and disappear.</div>

  <script>
    $(document).ready(function() {
      $("#hideBtn").click(function() {
        $("#panel").slideUp("slow", function() {
          console.log("The slide up animation is complete.");
        });
      });
    });
  </script>

</body>
</html>

To reverse or toggle the sliding effect, jQuery provides two companion methods:

  • slideDown(): Animates an element's height downward to reveal it.
  • slideToggle(): Toggles between slideUp() and slideDown() depending on the current visibility state of the element.