javascript get element distance from top code example

Example 1: javascript get element position relative to document

element.getBoundingClientRect().top + document.documentElement.scrollTop

Example 2: javascript element distance from top

function getPosition(element) {
    var xPosition = 0;
    var yPosition = 0;

    while(element) {
        xPosition += (element.offsetLeft - element.scrollLeft + element.clientLeft);
        yPosition += (element.offsetTop - element.scrollTop + element.clientTop);
        element = element.offsetParent;
    }

    return { x: xPosition, y: yPosition };
}