Skip to content

Instantly share code, notes, and snippets.

@allenhwkim
Created December 22, 2019 00:50
Show Gist options
  • Select an option

  • Save allenhwkim/97d7603b0121c7b8d9d84e9f9e59b15f to your computer and use it in GitHub Desktop.

Select an option

Save allenhwkim/97d7603b0121c7b8d9d84e9f9e59b15f to your computer and use it in GitHub Desktop.
Get Element Position Relative to Window
function getPosition (el) {
const rect = el.getBoundingClientRect();
const x = rect.left + window.scrollX;
const y = rect.top + window.scrollY;
return { x, y };
}
function getCenterPosition (el) {
const rect = el.getBoundingClientRect();
const x = rect.left + window.scrollX + (rect.width / 2);
const y = rect.top + window.scrollY + (rect.height / 2);
return { x: Math.floor(x), y: Math.floor(y) };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment