How to get value translateX by javascript

A cross browser solution:

function getTranslateXY(element) {
    const style = window.getComputedStyle(element)
    const matrix = new DOMMatrixReadOnly(style.transform)
    return {
        translateX: matrix.m41,
        translateY: matrix.m42
    }
}

Tests

We get this output (in a REPL style):

>> getTranslateXY(element1)
{translateX: 0, translateY: 0}
>> getTranslateXY(element2)
{translateX: 0, translateY: -90}
>> getTranslateXY(element3)
{translateX: 30, translateY: 0}
>> getTranslateXY(element4)
{translateX: 10, translateY: 20}
>> getTranslateXY(element5)
{translateX: -400, translateY: 500}

For those elements as arguments (passed to the aforementioned getTranslateXY function):

<div/>                                                         // element1 
<div style="transform: translateY(-90px);"/>                   // element2 
<div style="transform: translateX(30px);"/>                    // element3
<div style="transform: translateX(10px) translateY(20px);"/>   // element4
<div style="transform: translate3d(-400px, 500px, 0px);"/>     // element5

Pay attention to the mix (or absence) of translateX / translateY and also translate3d. We get proper results, no matter what CSS function we use (translate3d contains values of translateX and translateY).

Explanation

Reagrding the matrix: we have 16 properties named m11, m12, m13 ... m41, m42, m43, m44, that represent the columns and rows of the matrix. We are interested in the fourth column, and in the first and the second row. m41 holds the translateX property, and m42 holds the translateY property.

We use window.getComputedStyle(element) instead of element.style to get a uniformed representation of the transform value (in the form of a matrix), so we won't need to use regex, or parsing strings' headache.

Compatibility

Supported by all major browsers, except the notorious Internet Explorer, achieved by:

  • Using style.transform instead of style.webkitTransform.
  • Using DOMMatrixReadOnly interface instead of WebKitCSSMatrix. (WebKitCSSMatrix is an alias to DOMMatrix, which is a mutable version of DOMMatrixReadOnly, that inherits properties from it).

I made this summary thanks to the great answers and comments in this thread, so the credit is all yours.


You can use Window.getComputedStyle()

var myElement = document.querySelector('.hello');
// set inline-style transform to element
myElement.style.transform = "translateX(" + (-200) + "px) scaleX(" + 1.6 + ") scaleY(" + 1.2 + ")";

function getTranslateX() {
  var style = window.getComputedStyle(myElement);
  var matrix = new WebKitCSSMatrix(style.transform);
  console.log('translateX: ', matrix.m41);
}

document.querySelector('button').addEventListener('click', getTranslateX);
.hello {
    height: 100px;
    width: 100px;
    background: orange;
}
<div class="hello"></div>
<button type="button">get value</button>

Same as above example but using deprecated: style.webkitTransform

var myElement = document.querySelector('.hello');
myElement.style.transform = "translateX(" + (-200) + "px) scaleX(" + 1.6 + ") scaleY(" + 1.2 + ")";

function getTranslateX() {
  var style = window.getComputedStyle(myElement);
  var matrix = new WebKitCSSMatrix(style.webkitTransform);
  console.log('translateX: ', matrix.m41);
}

document.querySelector('button').addEventListener('click', getTranslateX);
.hello {
    height: 100px;
    width: 100px;
    background: orange;
}
<div class="hello"></div>
<button type="button">get value</button>

If you wonder why matrix.m41 that is explained here


If you want to be fancy (and, for that matter, exact), you can use a special method on the Window object. Namely, the .getComputedStyle() method.

Let's say your element has an id of myElement. You could get do as follows:

const myEl = document.getElementById('myElement');
window.getComputedStyle(myEl).transform;

Of course, what is returned reflects the collective effect of all other transformations applied upon the same element (e.g., rotations, translations, scalings, etc.). Furthermore, when querying for the value of transform style property, we tend to get something ugly in the form of a matrix transformation (e.g., "matrix3d(1, 0, 0, 0, 0, 0.939693, 0.34202, 0, 0, -0.34202, 0.939693, 0, 0, 0, 0, 1)"). We probably want to avoid this avenue since, at best, it leaves us with the hassle of having to parse a string output.

My recommendation, then, would be to stay simple and just query the transform property on the style object (more specifically, a CSSStyleDeclaration object). Check it:

const transformStyle = document.getElementById('myElement').style.transform
// => "translateX(1239.32px)"

Again, we get a string-type output, but the hassle has been greatly eased by the simplicity of that string. By leveraging the replace method of the String object's prototype and passing a simple regular expression, we can trim the value of transformStyle to just what we want:

const translateX = transformStyle.replace(/[^\d.]/g, '');
// => "1239.32"

And if you want that output as a Number data type, simply append the + unary operator before the whole statement to coerce into such:

const translateX_Val = +translateX;
// => 1239.32

Edit

Instead of doing

window.getComputedStyle(myEl).transform;

the safer and recommended approach is probably to instead use the getPropertyValue method:

window
  .getComputedStyle(myEl)
  .getPropertyValue('transform');

Tags:

Javascript