Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Get offset relative to selector or window
/**
* 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