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!


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

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']

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.