jQuery provides slide methods that allow you to create sliding effects for elements, making them appear or disappear with a sliding motion. These methods are particularly useful for creating dynamic, interactive UI components like menus or collapsible sections.
1. .slideUp()
The .slideUp()
method hides the selected elements with a sliding motion, effectively reducing their height to zero.
Syntax
$(selector).slideUp(speed, callback);
speed
: (Optional) The speed of the slide-up effect in milliseconds or predefined strings ("slow"
,"fast"
).callback
: (Optional) A function to execute after the slide-up is complete.
Example
$("button").click(function() { $("#myDiv").slideUp(1000); // Slides up over 1 second });
2. .slideDown()
The .slideDown()
method shows the selected elements with a sliding motion, effectively increasing their height from zero to the full height.
Syntax
$(selector).slideDown(speed, callback);
speed
: (Optional) The speed of the slide-down effect in milliseconds or predefined strings ("slow"
,"fast"
).callback
: (Optional) A function to execute after the slide-down is complete.
Example
$("button").click(function() { $("#myDiv").slideDown(1000); // Slides down over 1 second });
3. .slideToggle()
The .slideToggle()
method toggles between sliding up and sliding down the selected elements. If the element is visible, it will slide up; if hidden, it will slide down.
Syntax
$(selector).slideToggle(speed, callback);
speed
: (Optional) The speed of the slide effect in milliseconds or predefined strings ("slow"
,"fast"
).callback
: (Optional) A function to execute after the toggle is complete.
Example
$("button").click(function() { $("#myDiv").slideToggle(500); // Toggles slide effect over 0.5 seconds });
Examples of Slide Effects
Slide Up and Down
<button id="slideUpButton">Slide Up</button> <button id="slideDownButton">Slide Down</button> <div id="myDiv" style="width:200px;height:100px;background-color:red;"></div>
$("#slideUpButton").click(function() { $("#myDiv").slideUp("slow"); }); $("#slideDownButton").click(function() { $("#myDiv").slideDown("slow"); });