2

I am looking for a way to interrupt an animation and change the direction, something like:

var elem = document.getElementById('elem');
var rightwards = false;
var leftKeyframe = { transform: 'translate(0)' };
var rightKeyframe = { transform: 'translate(200px, 0)' };

function toggledirection() {
    rightwards = !rightwards;

    if (rightwards) {
        elem.animate([leftKeyframe, rightKeyframe], 1000);
    } else {
        elem.animate([rightKeyframe, leftKeyframe], 1000);
    }
}
div {
  width: 50px;
  height: 50px;
  border: 3px solid grey;
}
<div id="elem"></div>
<button onclick="toggledirection();">Toggle Direction</button>

However, notice how I have to define the start position of each animation, so when I interrupt a running animation the box jumps to the new start position and goes from there. I would like the box to just start from wherever it is currently like so (but this uses CSS animations, whereas I'm looking for a JS solution). The only method I have so far is to retrieve the current translation by parsing the transform string, but I was wondering if there was an easier way.

Community
  • 1
  • 1
woojoo666
  • 7,801
  • 7
  • 45
  • 57
  • http://caniuse.com/#feat=web-animation humm, I didn't know this API. However, why not a css/js solution like the example you shared in the "like so" link? – Sabaz Feb 10 '16 at 07:20
  • js animations have alot more power and flexibility, and they can even be [faster](https://css-tricks.com/myth-busting-css-animations-vs-javascript/) :O – woojoo666 Feb 10 '16 at 07:32

1 Answers1

1

I made few tests:
- here (JsFiddle) using the element computed style to reverse the animation.
- and here (JsFiddle) using the animate .reverse native method while checking the playState.

In the first fiddle I started a new animation every button click so, when you reverse while it's still transitioning, the animation will require 1 second to finish even if the element is 2 px far form the destination point.

also remember that window.getComputedStyle(element) !== element.style


Animation API:
- http://caniuse.com/#feat=web-animation
- https://developer.mozilla.org/en-US/docs/Web/API/Animation

getComputedStyle:
- https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle

Sabaz
  • 4,794
  • 2
  • 18
  • 26