Home > other >  How to return value from a css transform in js?
How to return value from a css transform in js?

Time:11-06

I'm trying to return a value from a css transform matrix in js.

The element is a div with the following css:

transform: translateY(-560px)

In my JS I'm currently getting the matrix by doing this:

  const el = document.querySelector('[data-holder]')
  return getComputedStyle(el).transform

Above code gives me:

matrix(1, 0, 0, 1, 0, -560)

How can i extract that last value from the matrix?

CodePudding user response:

Parsing computed CSS is brittle; you might receive different values in different browsers which would have to be catered for.

From the comments on your question, you state that the CSS is...

set in a js function

In that case, it would make sense to also record the relevant data in a more usable way. For example, using another data attribute

const translateY = -560;
el.style.transform = `translateY(${translateY}px)`;
el.dataset.transformTranslateY = translateY;

Then you can easily read this value back at a later time

const translateY = el.dataset.transformTranslateY;

CodePudding user response:

I'm adding this as an alternative approach, which gives direct access to the slot in the matrix we want.

const el = document.querySelector('[data-holder]')
const transformValue = el.style.transform;

// A matrix can be represnted like this:
// matrix(a, b, c, d, e, f)

// Prints the final number in the matrix
console.log(
 new DOMMatrix(transformValue).f
)

jsFiddle

  • Related