Vaggelis
Vaggelis

Reputation: 1011

How to animate slide down Jquery's addClass?

Any idea how to make it slide down ? i tried to pass second argument with a time but it swings it left. Should i use another method ?

$(document).on('click', '#bar', function () {
    
    $("#baz").addClass("foo");
    
});  
body{
height:200px;
position:relative;
}

.foo{
position:absolute;
bottom:0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
</head>
<body>
<button id="bar">PUSH IT DOWN</button>
<div id="baz">TEST</div>
</body>
</html>

Upvotes: 2

Views: 841

Answers (2)

dale landry
dale landry

Reputation: 8610

You can do this with CSS. Add an animation to your foo class and add an @keyframes rule for animating the tween of the position of the absolute positioned element. Just make sure the class you're adding foo, in your case, has a position set to the position you wish it to be when the animation is finished.

$(document).on('click', '#bar', function() {
  $("#baz").addClass("foo");
});
body {
  height: 200px;
  position: relative;
}

.foo {
  position: absolute;
  animation: slidedown .5s ease-in-out;
  bottom: 0;
}

@keyframes slidedown {
  0% {
    /* since the .foo class is set to bottom: 0, we will start at 0% to 160px*/
    bottom: 160px;
  }
  100% {
    /* we end at 0, which will be the bottom of the parent divs height */
    bottom: 0;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
</head>

<body>
  <button id="bar">PUSH IT DOWN</button>
  <div id="baz">TEST</div>
</body>

</html>

Upvotes: 1

Herbert Peters
Herbert Peters

Reputation: 179

jQuery has built in functionality for that. See https://api.jquery.com/slideDown/ for details and example

Upvotes: 0

Related Questions