1

ANSWER for the translateX value (thanks to Albert Portnoy):

var style = window.getComputedStyle(div);
var xVal = parseFloat(style.transform.split(" ")[4].replace(",", ''));

How do I get the current transform value of an element which is animated with @keyframes in javascript?

There doesn't seem to be a change of the css value I used (translateX) when it is animated or it has finished

<style>
    @keyframes anim {
        from {
            transform: translateX(0px)
        }

        to {
            transform: translateX(400px)
        }
    }

    div {
        width: 50px;
        height: 50px;
        background: black;
        animation: anim 5s forwards linear;
    }
</style>

<div></div>

<script>
    var div = document.getElementsByTagName('div')[0];

    function loop() {
        setTimeout(function () {
            console.log(div.style);
            loop()
        }, 100)
    }
    loop()

</script>
Servus
  • 479
  • 3
  • 13
  • Just get the [current translate position](https://stackoverflow.com/questions/42267189/how-to-get-value-translatex-by-javascript) – asportnoy May 25 '19 at 12:51
  • I'm not sure what you're trying to do but you can probably make use of animation events like [onanimationend](https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onanimationend) – Titus May 25 '19 at 12:53

1 Answers1

1

You can use (the not yet standard) feature CSSMatrix.
Another helpful explanation about Calculating element vertex data from CSS transforms

Here is a running example, note that i used requestanimationFrame instead of a callback loop with setTimeout to run the code on each frame.

var el = document.getElementById('root');
let count = 0;

function loop() {
  requestAnimationFrame(() => {
    var style = window.getComputedStyle(el);
    var matrix = new WebKitCSSMatrix(style.webkitTransform);
    console.log('translateX: ', matrix.m41);
    if(count > 100){
      // just to stop the infinite loop...
      return;
    }
    count++;
    loop();
  })
}
loop()
@keyframes anim {
  from {
    transform: translateX(0px)
  }
  to {
    transform: translateX(400px)
  }
}

#root {
  width: 50px;
  height: 50px;
  background: black;
  animation: anim 5s forwards linear;
}
<div id="root"/>
Sagiv b.g
  • 30,379
  • 9
  • 68
  • 99
  • Thanks for this answer. the requestAnimationFrame will certainly help with what I have to do. Is it even necessary to use the CSSMatrix? Does it have any advantages over style.transform.split(" ")[4].replace(",", ''); ? Thanks! – Servus May 25 '19 at 13:18