Created
March 21, 2023 16:55
-
-
Save celsowhite/00749b6b5e8247da5793121fb77237ea to your computer and use it in GitHub Desktop.
Get the coordinates of an element relative to the top of the page.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default function getElemCoords(elem) { | |
var box = elem.getBoundingClientRect(); | |
var body = document.body; | |
var docEl = document.documentElement; | |
var scrollTop = window.pageYOffset || docEl.scrollTop || body.scrollTop; | |
var scrollLeft = window.pageXOffset || docEl.scrollLeft || body.scrollLeft; | |
var clientTop = docEl.clientTop || body.clientTop || 0; | |
var clientLeft = docEl.clientLeft || body.clientLeft || 0; | |
var top = box.top + scrollTop - clientTop; | |
var left = box.left + scrollLeft - clientLeft; | |
return { | |
top: Math.round(top), | |
left: Math.round(left), | |
width: box.width, | |
height: box.height, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment