user850234 user850234 - 1 year ago 73
jQuery Question

Fetch the css value of transform directly using jquery

I am getting

-moz-transform: translate(-283.589px, 0px)
from dom by doing[vendor + 'Transform']
. Now i want to extract the value
to use it in my application but not getting the exact way to fetch it. If i do
it returns the matrix value as
matrix(1, 0, 0, 1, -283.589px, 0px)
. Is there a suitable way in jquery to directly fetch the value
. I dont want to do any matrix calculation.

Answer Source

I've got good news and bad news.

I'll start with the bad news: After examining the object that jQuery returns, the matrix object is nothing but a string and there's absolutely no way you can get another object but a string. As much we would like to disagree that it shouldn't be a string: CSS values are strings, hence jQuery returns strings.

So, whether you like it or not, you really have to parse the string in order to get the value. The good news is: I've got two solutions.

Now, if you're VERY sure that the first couple of values are ALWAYS the same you could simply use substring. But, next problem: in Google Chrome, the value -283.589px is being changed to -283.5889892578125.

Honestly, you need a more advanced string parser to get the correct value. I welcome regular expression:

var matrix = $('.selector').css('-moz-transform');
var values = matrix.match(/-?[\d\.]+/g);

This gets all the values of your string.

By selecting the right index, you can get your value:

var x = values[5];

That's the best solution I can provide and I'm positive it's the only possible solution.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download