get position of element relative to document 1

get position of element relative to document

function offset(el) {
    const rect = el.getBoundingClientRect(),
    scrollLeft = window.pageXOffset || document.documentElement.scrollLeft,
    scrollTop = window.pageYOffset || document.documentElement.scrollTop;
    return { top: + scrollTop, left: rect.left + scrollLeft }

// example use
const div = document.querySelector('div');
const divOffset = offset(div);

Here is what the above code is Doing:
1. We get the element’s bounding client rect.
2. We get the current scroll position of the page.
3. We add the scroll position to the bounding client rect to get the element’s position relative to the document.

Similar Posts