skip to Main Content

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?

2

Answers


  1. 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;
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search