23

I want to get translateY value from the in-line css with the JavaScript.

Here is the in-line value:

style ="transition-property: transform; transform-origin: 0px 0px 0px; transform: translate(0px, -13361.5px) scale(1) translateZ(0px);"

These code give to me the total list in to variable:

var tabletParent = document.getElementById("scroller");
var toTop = tabletParent.style.transform;
console.log(toTop);

console.log

translate(0px, -12358.8px) scale(1) translateZ(0px)

Expecting toTop as -12358.8px.

Gajus
  • 69,002
  • 70
  • 275
  • 438
Mo.
  • 26,306
  • 36
  • 159
  • 225
  • 1
    Have you tried *anything* yet? – Pointy Feb 20 '14 at 15:45
  • @Pointy Console.log result coming like this `translate(0px, -12358.8px) scale(1) translateZ(0px)` – Mo. Feb 20 '14 at 15:48
  • When I check via Firefox or Chrome (which, by the way, will require `-webkit-transform` instead of just `transform`) I get a `matrix()` function back. – Pointy Feb 20 '14 at 15:52

6 Answers6

25

There are multiple ways. One of the first that come to my mind is parsing the string you get.

For example:

function getTranslateZ(obj)
{
    var style = obj.style,
        transform = style.transform || style.webkitTransform || style.mozTransform,
        zT = transform.match(/translateZ\(([0-9]+(px|em|%|ex|ch|rem|vh|vw|vmin|vmax|mm|cm|in|pt|pc))\)/);
    return zT ? zT[1] : '0';
    //Return the value AS STRING (with the unit)
}
// getTranslateZ(tabletParent) => '0px'

However this will only work with translateZ explicitly defined (not translate3d nor matrix3d). A most consistent way might be getComputedStyle, but this would always get the value in px unit and thus is only truely valid at the time you compute it (a window resize can change it):

function getComputedTranslateZ(obj)
{
    if(!window.getComputedStyle) return;
    var style = getComputedStyle(obj),
        transform = style.transform || style.webkitTransform || style.mozTransform;
    var mat = transform.match(/^matrix3d\((.+)\)$/);
    return mat ? ~~(mat[1].split(', ')[14]) : 0;
    // ~~ casts the value into a number
}
// getComputedTranslateZ(tabletParent) => 0

See this fiddle showing both methods (note that I've been using chrome for the tests, so I've prefixed your CSS with -webkit-).


EDIT:
To get translateY, if your visitors browser is recent enough to support getComputedStyle, you could change my getComputedTranslateZ function to handle both matrix and matrix3d values. It is simpler than trying to parse every possible css strings (translateY, translate, translate3d, matrix, matrix3d):

function getComputedTranslateY(obj)
{
    if(!window.getComputedStyle) return;
    var style = getComputedStyle(obj),
        transform = style.transform || style.webkitTransform || style.mozTransform;
    var mat = transform.match(/^matrix3d\((.+)\)$/);
    if(mat) return parseFloat(mat[1].split(', ')[13]);
    mat = transform.match(/^matrix\((.+)\)$/);
    return mat ? parseFloat(mat[1].split(', ')[5]) : 0;
}
Bali Balo
  • 3,338
  • 1
  • 18
  • 35
  • Thanks for your effort :) actually I am looking for the solution for `translateY` value which is from `translate(0px, -12358.8px)` – Mo. Feb 20 '14 at 16:27
  • See my edited answer to do it using `getComputedStyle`. – Bali Balo Feb 20 '14 at 16:35
  • how to get translateX value? –  Jun 29 '16 at 17:30
  • @alireza-valizade Change index 5 to 4 in getComputedTranslateY function: `return mat ? parseFloat(mat[1].split(', ')[4]) : 0;` – tugce Sep 06 '16 at 00:09
  • @tugce why? he needed tY which is at 5th index https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/matrix – Denis Oct 03 '16 at 18:44
7

If you want the raw value without 'px' you could use a regex like this:

var transZRegex = /\.*translateZ\((.*)px\)/i;

and get the value like this:

var zTrans = transZRegex.exec(test)[1];

Here is a jsFiddle demonstrating.

rusmus
  • 1,665
  • 11
  • 18
6
function getTranslateXValue(translateString){

  var n = translateString.indexOf("(");
  var n1 = translateString.indexOf(",");

  var res = parseInt(translateString.slice(n+1,n1-2));

return res;

}
function getTranslateYValue(translateString){

 var n = translateString.indexOf(",");
  var n1 = translateString.indexOf(")");

  var res = parseInt(translateString.slice(n+1,n1-1));
return res;

}
il_raffa
  • 5,090
  • 129
  • 31
  • 36
2

There is now a DOM API that provides a typed solution for this known as the CSS Object Model see here.

Part of that spec specifies a attributeStyleMap which you can use to get typed values for a transform value (or anything else).

const node = document.querySelector('#something')

const attrs = node.attributeStyleMap.get('transform')
if (!attrs) return

const translation = Array.from(attrs.values())
    .find(attr => attr instanceof CSSTranslate)

console.log(translation.x); // { value: 115, unit: 'px' }
nikk wong
  • 8,059
  • 6
  • 51
  • 68
0

You may have to work out x and y of .slice(x,y) if you have more than one translate property

  const trsString = element.style.transform; //eg "translateY(36px)"
  let num = trsString.slice(11, trsString.length - 3) 
  num = num.length == 0 ? 0 : parseInt(num) // will be 36
Servus
  • 479
  • 3
  • 13
0

to get the raw value without 'px' you can use this:

function extractTranslateFromTransform(transform) {
    let translateValue = null;
    let translate = transform.match(/translate\(.*\)/)?.[0];
    if (translate) {
        translateValue = {};
        if (translate.indexOf(',') !== -1) {
            translateValue.x = parseFloat(translate.substring(translate.indexOf('(') + 1, translate.indexOf(',')));
            translateValue.y = parseFloat(translate.substring(translate.indexOf(',') + 1));
        } else {
            translateValue.x = translateValue.y = parseFloat(translate.substring(translate.indexOf('(') + 1));
        }
    }
    return translateValue;
}

const translate = extractTranslateFromTransform(document.getElementById('divWithTransform').style.transform);

console.log(translate);
<div id="divWithTransform" style="transform: translate(0px, -13361.5px) scale(1) translateZ(0px);" />
adl
  • 1,865
  • 1
  • 25
  • 32