Skip to content

Instantly share code, notes, and snippets.

@dmail
Created April 5, 2018 12:38
Show Gist options
  • Select an option

  • Save dmail/b478faf3a471f6eb7cd54e4ae02ee1e3 to your computer and use it in GitHub Desktop.

Select an option

Save dmail/b478faf3a471f6eb7cd54e4ae02ee1e3 to your computer and use it in GitHub Desktop.
get element position relative to an other
// keep in mind element may be inside an iframe
// var childWindow = elem.document.frames.window;
// while (childWindow != parentWindow) {
// offset.left = offset.left + childWindow.frameElement.getBoundingClientRect().left;
// offset.top = offset.top + childWindow.frameElement.getBoundingClientRect().top;
// childWindow = childWindow.parent;
// }
const getRelativeBoundingClientRect = (element, relativeElement) => {
const { left, top, right, bottom } = element.getBoundingClientRect()
const {
left: relativeLeft,
top: relativeTop,
right: relativeRight,
bottom: relativeBottom
} = relativeElement.getBoundingClientRect()
return {
left : left - relativeLeft,
top : top - relativeTop,
right : relativeRight - right,
bottom : relativeBottom - bottom,
}
}
const getOffsetParentPosition = (element) => {
return getRelativeBoundingClientRect(element, element.offsetParent)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment