How to create jQuery slide up and down toggle effect

Topic: JavaScript / jQuery« Prev|Next »

Answer: Use the jQuery slideUp() and slideDown() methods

You can use the jQuery slideUp() and slideDown() methods to hide and show the elements with a smooth sliding motion using a single line of code.

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  • <meta charset="utf-8">
  • <title>jQuery slideUp and slideDown Effect</title>
  • <style type="text/css">
  •     .box{
  •         width: 400px;
  •         background: #f0e68c;
  •         border: 1px solid #a29415;
  •     }
  •     .box-inner{
  •         padding: 10px;
  •     }
  • </style>
  • <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
  • <script type="text/javascript">
  •     $(document).ready(function(){
  •         $(".slide-up").click(function(){
  •             $(".box").slideUp();
  •         });
  •         $(".slide-down").click(function(){
  •             $(".box").slideDown();
  •         });
  •     });
  • </script>
  • </head>
  • <body>
  •     <button type="button" class="slide-up">Slide Up</button>
  •     <button type="button" class="slide-down">Slide Down</button>
  •     <hr>
  •     <div class="box">
  •         <div class="box-inner">Lorem ipsum dolor sit amet...</div>
  •     </div>
  • </body>
  • </html>

Alternatively, you can use the jQuery slideToggle() method that perform both slide up and down animation in such a way that if the element is initially displayed, it will be hidden; and if it is hidden, it will be shown. Here's an example:

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  • <meta charset="utf-8">
  • <title>jQuery slideToggle Effect</title>
  • <style type="text/css">
  •     .box{
  •         width: 400px;
  •         background: #f0e68c;
  •         border: 1px solid #a29415;
  •     }
  •     .box-inner{
  •         padding: 10px;
  •     }
  • </style>
  • <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
  • <script type="text/javascript">
  •     $(document).ready(function(){
  •         $(".slide-toggle").click(function(){
  •             $(".box").slideToggle();
  •         });
  •     });
  • </script>
  • </head>
  • <body>
  •     <button type="button" class="slide-toggle">Slide Toggle</button>
  •     <hr>
  •     <div class="box">
  •         <div class="box-inner">Lorem ipsum dolor sit amet...</div>
  •     </div>
  • </body>
  • </html>

Related FAQ

Here are some more FAQ related to this topic:

 
Close

Your Feedback:

 

We would love to hear from you! Please say something.