jQuery Slide
Sliding effects make an element appear to roll open or fold shut by animating its height. They are perfect for accordions, dropdown menus, and expandable FAQ answers. jQuery offers three sliding methods: slideDown(), slideUp(), and slideToggle(). This lesson walks through each and shows how they differ from hide, show, and fade.
Sliding elements open and closed
slideDown() reveals a hidden element by animating its height from zero up to its natural size, giving the impression of a panel unrolling. slideUp() does the reverse, shrinking the height down to zero before hiding the element completely. Because the animation works on height, the content below the element moves up or down smoothly to fill the space, which feels natural to users.
slideDown() and slideUp()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<button id="openBtn">Open</button>
<button id="closeBtn">Close</button>
<div id="panel" style="display:none;">Panel content</div>
<script>
$("#openBtn").click(function() {
$("#panel").slideDown("slow");
});
$("#closeBtn").click(function() {
$("#panel").slideUp(600);
});
</script>
</body>
</html>As with the other effect methods, slideDown() and slideUp() take an optional speed and callback. A common pattern is to build a menu where the header stays visible and the body slides open when clicked. For that, slideToggle() is ideal because it opens a closed panel and closes an open one with the same line of code.
slideToggle() for an accordion header
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div class="accordion-header">Section 1</div>
<div class="accordion-body" style="display:none;">Accordion body content</div>
<script>
$(".accordion-header").click(function() {
$(this).next(".accordion-body").slideToggle(300);
});
</script>
</body>
</html>How sliding differs from fading
- slideDown() animates height from 0 to full and shows the element.
- slideUp() animates height down to 0, then hides the element.
- slideToggle() switches between the slid-down and slid-up states.
- Sliding changes height, so surrounding content reflows; fading only changes opacity.
- All three methods accept an optional speed and a callback function.
Exercise: jQuery Slide
What does .slideDown() do to a hidden element?