Get the value of -webkit-transform of an element with jquery
Asked Answered
S

6

39

I'm manipulating a div with the new cool css3 way of doing a transform like this:

$("#thediv").css("-webkit-transform","translate(-770px, 0px)");

Later on in the script I thought to get the value of the transform like this:

$("#thediv").css("-webkit-transform");

It returns a matrix like this: matrix(1, 0, 0, 1, -770, 0)

What I can't figure out is how to get the 5th value (-770) of this matrix...

Any suggestions? Thanks!

Sacramental answered 11/5, 2011 at 17:30 Comment(0)
S
61

Your matrix is a 4x4 transformation matrix:

matrix stuff

The -770 corresponds to the vx. To extract it, construct a WebkitCSSMatrix object:

var style = window.getComputedStyle($('#thediv').get(0));  // Need the DOM object
var matrix = new WebKitCSSMatrix(style.webkitTransform);

console.log(matrix.m41);  // -770
Salish answered 11/5, 2011 at 17:39 Comment(7)
Thank you. To save time somebody looking for translateY, it's matrix[5].Asbestos
WebKitCSSMatrix is not supported by Firefox or OperaCadaverous
@koosa: Well, yeah. Neither of them use the WebKit rendering engine. I don't think they have equivalents to WebKitCSSMatrix.Salish
@Salish - yep so I think yckart's answer might be better to use for the momentCadaverous
You shouldn't just give a Chrome/Safari answer without actually stating that. This answer is pretty useless in everyday web development.Tackett
@30secondstosam: The question was tagged webkit and my answer clearly uses WebKitCSSMatrix, so what's the issue?Salish
There is an alternative: Just replace WebKitCSSMatrix with the alternate DOMMatrix. See here: developer.mozilla.org/en-US/docs/Web/API/DOMMatrixQuadruped
J
30

You could split the string into an array and get the desired value as usual. Here's a little helper function that does the split part.

function matrixToArray(str) {
  return str.match(/\d+/g);
}

Update

To preserve decimals: rgba(0, 0, 0, 0.5)

and negatives: matrix(1, 0, 0, 1, -770, 0)

function matrixToArray(str) {
  return str.split('(')[1].split(')')[0].split(',');
}

Update2

RegExp based solution that preserves decimal and negative numbers:

function matrixToArray(str) {
  return str.match(/(-?[0-9\.]+)/g);
}

matrixToArray('rgba(0, 0, 0, 0.5)'); // => ['0', '0', '0', '0.5']
matrixToArray('matrix(1, 0, 0, 1, -770, 0)'); // => ['1', '0', '0', '1', '-770', '0']
Janicejanicki answered 18/1, 2013 at 10:35 Comment(2)
This is a much more flexible solution, and the Update 2 example is very useful, because usually iterating over the various matches of a RegExp.exec is a lot more hazardous. +10 if I could.Cob
I think this answer is much better than the one above for most purposes.Aggravate
B
2

I would recommend using the WebkitCSSMatrix object. http://developer.apple.com/library/safari/#documentation/AudioVideo/Reference/WebKitCSSMatrixClassReference/WebKitCSSMatrix/WebKitCSSMatrix.html#//apple_ref/doc/uid/TP40009363

This object has as its attributes the matrix elements. It also provides convenience functions for various transformations.

Boatwright answered 11/5, 2011 at 17:34 Comment(2)
Looks also nice, but a little bit to complicated right now. Thanks anyway!Sacramental
Sorry, as of today, that link is broken :(Offing
K
2

The reason you get the matrix string value, is that jQuery's css function is obtaining the computed style (the result of window.getComputedStyle($("#thediv")[0]).webkitTransform).

To get the actual string value which you set it to in the previous call ("translate(-770px, 0px)") you can use:

var t = $("#thediv")[0].style.webkitTransform;

From that you could just use string methods to get the x value, e.g:

t.substring(t.indexOf("(") + 1, t.indexOf(",") - 2)

which gives -770. However, note that this is only acceptable if you know that the value exists and is in the form you're using (with just a translate(xpx, ypx), since other values are valid!

If you'd prefer to use the computed style, then (to add to @Maz's suggestion), to get the 5th value (the x transform), you can do:

new WebKitCSSMatrix($("#thediv").css("-webkit-transform")).e;

To get the sixth one (the y transform) you use the f property of the matrix.

Kafka answered 5/2, 2013 at 11:37 Comment(3)
Is this method of getting the original string value going to work across all major browsers?Zealotry
Unfortunately not.. generally anything with a "vendor prefix" (e.g. "ms", "webkit", "o", "moz") is platform specific.Kafka
In any case, I found an alternate solution to my original problem, which was animating the transformation: fiddle (not my code)Zealotry
D
2

Since I constantly need to use jQuery together with TweenMax and since TweenMax already took care of all the parsing of various types of transformation strings as well as compatibility issues, I wrote a tiny jquery plugin here (more of a wrap up of gsap's) that could directly access these values like this:

$('#ele').transform('rotationX') // returns 0
$('#ele').transform('x')         // returns value of translate-x

The list of properties you could get/set, along with their initial properties:

perspective: 0
rotation: 0
rotationX: 0
rotationY: 0
scaleX: 1
scaleY: 1
scaleZ: 1
skewX: 0
skewY: 0
x: 0
y: 0
z: 0
zOrigin: 0

Paste from my other answer, hope this helps.

Drying answered 16/10, 2014 at 1:22 Comment(0)
E
-1

I have coded the simplest solution that ALSO works in Safari, Chrome AND Firefox :)

The trick is NOT to reference the

.css("transform")

but the

.css("translate")

property instead :

var matrix = $("#thediv").css('translate');
console.log ( matrix[1] ); 
// matrix result is of form [x , y]
// so for example matrix[1] will give you the transformY value :)
$('html,body').animate({scrollTop: matrix[1]}, 750);

I'm delighted to have found such an economical solution since I have been dealing with 3D transforms in webkit and 2D transforms in Firefox simultaneously, and using this method the property values can be accessed directly :)

Efthim answered 26/11, 2014 at 4:0 Comment(2)
chrome -> $(element).css('transform') = "matrix(1, 0, 0, 1, -759.640625, 0)" $(element).css('translate') = undefinedGullett
This gives me undefined as well.Swane

© 2022 - 2024 — McMap. All rights reserved.