Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get translate3d values of a div?

Say a div has this applied to it:

-webkit-transform: translate3d(0px, -200px, 0px)

How could I retrieve those values with jQuery?

like image 936
fancy Avatar asked Nov 02 '11 14:11

fancy


3 Answers

I don't know about the various edge cases, but in my case it's always 3 values like 'translate3d(23px, 34px, 40px)', so this was the cleanest way I could find:

function getMatrix(element) {
    const values = element.style.transform.split(/\w+\(|\);?/);
    const transform = values[1].split(/,\s?/g).map(parseInt);

    return {
      x: transform[0],
      y: transform[1],
      z: transform[2]
    };
}

Result:

{x: 238, y: 0, z: 0}
like image 170
parliament Avatar answered Nov 11 '22 19:11

parliament


If you change the accepted answer's match() pattern to this it adds support for negative numbers:

$(el).css('-webkit-transform').match(/matrix(?:(3d)\(-{0,1}\d+(?:, -{0,1}\d+)*(?:, (-{0,1}\d+))(?:, (-{0,1}\d+))(?:, (-{0,1}\d+)), -{0,1}\d+\)|\(-{0,1}\d+(?:, -{0,1}\d+)*(?:, (-{0,1}\d+))(?:, (-{0,1}\d+))\))/)
like image 14
Trevor Lundeen Avatar answered Nov 11 '22 20:11

Trevor Lundeen


The value gets stored either as a matrix or a matrix3d, depending on whether or not the z value was set. Assuming no other transformations, for a 2D matrix, X and Y are the last two values. For a 3D matrix, X, Y, Z, 1 are the last four digits.

You could use a regular expression to get the values:

function getTransform(el) {
    var results = $(el).css('-webkit-transform').match(/matrix(?:(3d)\(\d+(?:, \d+)*(?:, (\d+))(?:, (\d+))(?:, (\d+)), \d+\)|\(\d+(?:, \d+)*(?:, (\d+))(?:, (\d+))\))/)

    if(!results) return [0, 0, 0];
    if(results[1] == '3d') return results.slice(2,5);

    results.push(0);
    return results.slice(5, 8);
}
like image 12
Brian Nickel Avatar answered Nov 11 '22 21:11

Brian Nickel