erezT erezT - 6 months ago 50
Javascript Question

How to select the sub attribute of CSS3 matrix transform with jQuery

My

.test
class looks like this:

.test {
transform-style: preserve-3d;
width: 460px;
height: 738px;
transform: translate3d(0px, 0px, 480.89px)
matrix3d(-0.959423, 0.0701992, -0.273093, 0, 0, -0.968514, -0.248959, 0, 0.281971, 0.238857, -0.929215, 0, 0, 0, 0, 1)
translate3d(230px, 369px, 0px);
}


Since
matrix3d
is dynamic, I'm trying to listen for changes of the 3rd array member of
matrix3d
and run a conditional if statement on it. How can this be done?

Answer

You can use getComputedStyle to get the value of the transform property and then split it (or use a RegEx, whichever you prefer) to obtain the individual values like in the below snippet.

var el = document.querySelector('.test'),
  op = document.querySelector('output'),
  btn = document.querySelector('.change'),
  oldparams, newparams;

window.onload = function() {

  /* get matrix on load */
  oldparams = getMatrix();
  op.innerHTML += 'Original Matrix Row 3: ' + oldparams[8] + ',' + oldparams[9] + ',' + oldparams[10] + ',' + oldparams[11]; /* since array is 0 based, 8 - 11 is the 3rd row. */

  /* on click of button, change matrix and get the changed value */
  btn.addEventListener('click', function() {
    el.style.transform = 'translate3d(0px, 0px, 480.89px) matrix3d(-0.959423, 0.0701992, -0.273093, 0, 0, -0.968514, -0.248959, 0, 0.383571, 0.578857, -0.639215, 0, 0, 0, 0, 1) translate3d(230px, 369px, 0px)';
    newparams = getMatrix();
    op.innerHTML += '<br><br> New Matrix Row 3: ' + newparams[8] + ', ' + newparams[9] + ', ' + newparams[10] + ', ' + newparams[11]; /* since array is 0 based, 8 - 11 is the 3rd row. */
  });
}

function getMatrix() {
  var matrix = window.getComputedStyle(el).transform;
  /*op.innerHTML = 'Matrix Transform is:' + matrix; */

  var params = matrix.split('(')[1].split(')')[0].split(',');
  return params;
}
.test {
  transform-style: preserve-3d;
  width: 460px;
  height: 738px;
  transform: translate3d(0px, 0px, 480.89px) matrix3d(-0.959423, 0.0701992, -0.273093, 0, 0, -0.968514, -0.248959, 0, 0.281971, 0.238857, -0.929215, 0, 0, 0, 0, 1) translate3d(230px, 369px, 0px);
}
<h2>Output</h2>
<output></output>
<button class='change'>Change Matrix</button>
<div class='test'>Some text</div>

Comments