Lucas Gruwez Lucas Gruwez - 2 months ago 7
Javascript Question

jQuery not animating back up

I have a box that should fade in and move up when clicked, but instead, it just stays down. The fading works...

Thanks for your help !



var fadeInDown = function (element, duration, easing) {
element.css({
opacity: '0',
webkitTransform: 'translateY(100%)',
transform: 'translateY(100%)',
})
.animate({
opacity: '1',
webkitTransform: 'translateY(0%)',
transform: 'translateY(0%)',
}, duration, easing);
};

$('.box').click(function () {
fadeInDown($('.box'), 400, 'swing');
});

body {
display: flex;
justify-content: center;
}

.box {
width: 200px;
height: 200px;
background: pink;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div class="box"></div>




Answer

jQuery's animate doesn't support css transforms like this. You'd need to introduce a step function, to animate it. This should be something close to what you're looking for:

var fadeInDown = function (element, duration, easing) {
  element.css({
    opacity: '0',
    webkitTransform: 'translateY(0%)',
    transform: 'translateY(0%)',
  })
  .animate({
    opacity: '1'
  }, {
    duration: duration,
    step: function(now, fx) {
      var step = 100*now;
      $(this).css({
        webkitTransform: 'translateY(' + step + '%)',
        transform: 'translateY(' + step + '%)'
      });
    }
  }, easing);
};

$('.box').click(function () {
  fadeInDown($('.box'), 400, 'swing');
});
body {
  display: flex;
  justify-content: center;
}

.box {
  width: 200px;
  height: 200px;
  background: pink;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div class="box"></div>

Also, take a look at this question, which may give you some additional help.