Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to return value from a css transform in js?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading