Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the value of -webkit-transform of an element with jquery

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!

like image 730
Matthias Loibl Avatar asked May 11 '11 17:05

Matthias Loibl


People also ask

How do I get text inside a div using jQuery?

To get the value of div content in jQuery, use the text() method. The text( ) method gets the combined text contents of all matched elements. This method works for both on XML and XHTML documents.

What does VAL () do in jQuery?

val() method is primarily used to get the values of form elements such as input , select and textarea . When called on an empty collection, it returns undefined . When the first element in the collection is a select-multiple (i.e., a select element with the multiple attribute set), .

How do I set the value of a element in jQuery?

JQuery val() method: This method return/set the value attribute of selected elements. If we use this method to return value, it will return the value of the FIRST selected element. If we use this method to set value, it will set one or more than one value attribute for set of selected elements.


2 Answers

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 
like image 164
Blender Avatar answered Sep 27 '22 18:09

Blender


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'] 
like image 35
yckart Avatar answered Sep 27 '22 17:09

yckart