Created
October 22, 2021 11:15
-
-
Save Ciantic/a5ab847a2b9929a41046c60504aaf4ff to your computer and use it in GitHub Desktop.
Get offset relative to selector or window
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
/** | |
* Get offset relative to selector (or window) | |
* | |
* @param {HTMLElement} el | |
* @param {string|undefined} selector if not give, assumes root most (window) | |
*/ | |
function offsetRelativeTo(el, selector) { | |
let offsetTop = el.offsetTop; | |
let offsetLeft = el.offsetLeft; | |
let offsetParent = el.offsetParent; | |
for (let index = 0; index < 100; index++) { | |
if (!offsetParent) { | |
// console.log("No more parents?"); | |
break; | |
} | |
offsetTop += offsetParent.offsetTop - offsetParent.scrollTop; | |
offsetLeft += offsetParent.offsetLeft - offsetParent.scrollLeft; | |
offsetParent = offsetParent.offsetParent; | |
if (offsetParent && typeof selector !== "undefined" && offsetParent.matches(selector)) { | |
// console.log("Found the parent!"); | |
break; | |
} | |
} | |
return { | |
top: offsetTop, | |
left: offsetLeft, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment