Skip to content

Instantly share code, notes, and snippets.

@aderaaij
Last active February 12, 2023 15:19
Show Gist options
  • Save aderaaij/a6b666bf756b2db1596b366da921755d to your computer and use it in GitHub Desktop.
Save aderaaij/a6b666bf756b2db1596b366da921755d to your computer and use it in GitHub Desktop.
Get the computed Translate X and Y values of a given DOM element. Based on https://stackoverflow.com/questions/21912684/how-to-get-value-of-translatex-and-translatey
function getTranslate(item: HTMLElement): number | number[] | undefined {
const transArr = [];
if (!window.getComputedStyle) {
return;
}
const style = window.getComputedStyle(item);
const transform = style.transform || style.webkitTransform;
let mat = transform.match(/^matrix3d\((.+)\)$/);
if (mat) {
return parseFloat(mat[1].split(', ')[13]);
}
mat = transform.match(/^matrix\((.+)\)$/);
mat ? transArr.push(parseInt(mat[1].split(', ')[4], 10)) : transArr.push(0);
mat ? transArr.push(parseInt(mat[1].split(', ')[5], 10)) : transArr.push(0);
return transArr;
}
@neofuture
Copy link

neofuture commented Aug 1, 2020

Typescript Version

getTranslate(item): any {
    const transArr = [];
    if (!window.getComputedStyle) {
      return;
    }
    const style = window.getComputedStyle(item);
    const transform = style.transform || style.webkitTransform || style.mozTransform || style.msTransform;
    let mat = transform.match(/^matrix3d\((.+)\)$/);
    if (mat) {
      return parseFloat(mat[1].split(', ')[13]);
    }
    mat = transform.match(/^matrix\((.+)\)$/);
    mat ? transArr.push(parseInt(mat[1].split(', ')[4], 10)) : transArr.push(0);
    mat ? transArr.push(parseInt(mat[1].split(', ')[5], 10)) : transArr.push(0);

    return transArr;
  }

@aderaaij
Copy link
Author

aderaaij commented Aug 3, 2020

@neofuture that would kinda defy the point of TS. It would be more beneficial to type the return and argument.

function getTranslate(item: HTMLElement): number | number[] | undefined {
    const transArr = [];
    if (!window.getComputedStyle) {
      return;
    }
    const style = window.getComputedStyle(item);
    const transform = style.transform || style.webkitTransform;
    let mat = transform.match(/^matrix3d\((.+)\)$/);
    if (mat) {
      return parseFloat(mat[1].split(', ')[13]);
    }
    mat = transform.match(/^matrix\((.+)\)$/);
    mat ? transArr.push(parseInt(mat[1].split(', ')[4], 10)) : transArr.push(0);
    mat ? transArr.push(parseInt(mat[1].split(', ')[5], 10)) : transArr.push(0);

    return transArr;
  }

@neofuture
Copy link

Maybe but to save some one changing it, if they do need it

@jhsware
Copy link

jhsware commented Jun 8, 2021

const transArr = [];

It appears you need to type this to avoid type errors further down:

const transArr: number[] = [];

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment