0

The Web Animations API has the reverse method which allows the running animation to be played back in the opposite direction it is currently headed.

However I have a scenario where I would just like to play a defined animation backwards. At present, I am accomplishing this by checking if the animation is going forwards or backwards first and then doing the opposite but this feels wonky!

Is there an established pattern for just asking a defined animation to run backwards (and not necessarily run in reverse from its current playhead)?

In code example below, if you are on the first instance (idx === 0) I check if you are going forwards by checking if playbackRate is 1 first. Without this, the animation would run backwards first.

Feels like there should be a simpler way of running an animation backwards when required — is there?

var box = document.querySelector(".thing");
var btn = document.querySelector("button");
var span = document.querySelector("span");
const move = box.animate(
    [{ transform: "translate(0px, 0px)" }, { transform: "translate(100px, 0px)" }],
    { duration: 500, fill: "both" }
);
move.pause();

let idx = 0;

function choose() {
    if (idx === 0) {
        move.playbackRate === 1 ? move.play() : move.reverse();
    } else {
        move.reverse();
    }
}

btn.addEventListener("click", () => {
    choose();
    idx = idx === 0 ? 1 : 0;
    span.textContent = idx;
});
.thing {
    width:49px;
    height: 49px;
    background-color: red;
}
<div class="thing"></div>
<button type="button">ClickMe</button>
<span>0</span>
Ben Frain
  • 2,510
  • 1
  • 29
  • 44
  • Isn't reverse the same as backwards? The wording is confusing to me. – Rob Oct 02 '20 at 12:31
  • It is confusing! reverse takes the current position and goes in the opposite direction. Backwards always goes backwards through the keyframes – Ben Frain Oct 02 '20 at 12:34

1 Answers1

0

I believe you want the direction property, e.g.

move.effect.updateTiming({ direction: 'reverse' });
brianskold
  • 809
  • 5
  • 10