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>
2
  • Just get the current translate position Commented May 25, 2019 at 12:51
  • I'm not sure what you're trying to do but you can probably make use of animation events like onanimationend Commented May 25, 2019 at 12:53

1 Answer 1

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"/>

Sign up to request clarification or add additional context in comments.

1 Comment

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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.