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!
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.
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), .
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.
Your matrix is a 4x4 transformation matrix:
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With