Skip to content

Instantly share code, notes, and snippets.

@branneman
Last active April 13, 2016 13:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save branneman/d21a69d0e80fc5a30f9625c05b5c621b to your computer and use it in GitHub Desktop.
Save branneman/d21a69d0e80fc5a30f9625c05b5c621b to your computer and use it in GitHub Desktop.
/**
* @param {HTMLElement} element - The element's coordinates to calulate
* @param {HTMLElement} relativeElement - An optional relative element, defaults to `document.body`
* @returns {{ offsetY: Number, offsetX: Number }}
*/
const getElementCoordinates = function(element, relativeElement = document.body) {
const relativeRect = relativeElement.getBoundingClientRect();
const elementRect = element.getBoundingClientRect();
const offsetY = elementRect.top - relativeRect.top;
const offsetX = elementRect.left - relativeRect.left;
return { offsetY, offsetX };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment