Anime.js how to reverse this animation?

maria di cesare picture maria di cesare · May 22, 2018 · Viewed 7.6k times · Source

I've recently started working with Anime.js to animate my designs and I´ve been stuck in this for a while now, bet for many this is very simple! I have a button that enlarges my div and would like to have the div in its initial state if the icon is clicked again. My HTML:

Answer

Andrew Bone picture Andrew Bone · May 22, 2018

It is shame there is no built-in toggle function but there is a reverse function what this does is toggle the internal attribute reversed which, in turn, controls what the play function does.

In theory, you can just call reverse after play like so

var boxGetsLarger = anime({
  targets: '.agent-button',
  width: {
    value: '+=300',
    duration: 200,
    easing: 'linear'
  },
  borderRadius: {
    value: 83
  },
  duration: 200,
  height: {
    value: '+=20'
  },
  easing: 'linear',
  autoplay: false
});

document.querySelector('.agent-button').onclick = function() {
  boxGetsLarger.play();
  boxGetsLarger.reverse();
}
.agent-button {
  display: flex;
  justify-content: space-between;
  border-radius: 100px;
  background: #ffffff;
  box-shadow: 0pt 2pt 10pt #0000001f;
  height: 91px;
  width: 91px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/2.2.0/anime.min.js"></script>
<div class="agent-button close">
  <img src="img/audio-bars.svg">
</div>

Only I found reverse was running before play was finished leading to some strange behaviour, I'd recommend taking advantage of the 'finished' promise built-in like so

var boxGetsLarger = anime({
  targets: '.agent-button',
  width: {
    value: '+=300',
    duration: 200,
    easing: 'linear'
  },
  borderRadius: {
    value: 83
  },
  duration: 200,
  height: {
    value: '+=20'
  },
  easing: 'linear',
  autoplay: false
});

document.querySelector('.agent-button').onclick = function() {
  boxGetsLarger.play();
  boxGetsLarger.finished.then(() => {
    boxGetsLarger.reverse();
  })
}
.agent-button {
  display: flex;
  justify-content: space-between;
  border-radius: 100px;
  background: #ffffff;
  box-shadow: 0pt 2pt 10pt #0000001f;
  height: 91px;
  width: 91px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/2.2.0/anime.min.js"></script>
<div class="agent-button close">
  <img src="img/audio-bars.svg">
</div>

This will now only reverse the direction when play is finished.

I hope you find this helpful.