get position of element 1

get position of element

// Without Jquery

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

// example use
var div = document.querySelector('div');
var divOffset = offset(div);
console.log(divOffset.left, divOffset.top);

Here is what the above code is Doing:
1. Get the element’s bounding rectangle.
2. Get the window’s scroll position.
3. Add the scroll position to the element’s bounding rectangle.
4. Return the element’s bounding rectangle.

Similar Posts