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.