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?
>Solution :
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;