Javascript to calculate pixel distance between top of div and top of document

Viewed 89

As the title says, is there any function or simple method to calculate pixel distance between the top of a div and the top of the HTML document? All the questions I've seen on stackoverflow do it for top of div and top of viewport which is different than what I need. Thanks in advance.

1 Answers

Here is a function you could use, but I'm not sure it works on all contexts :

function topRelativeToDocumentElement(element) {
    var curCss, t=0;
    while (element!==null && element!==document.documentElement) {
        if ((defaultView=element.ownerDocument.defaultView) && (computedStyle=defaultView.getComputedStyle(element, null))) {
            curCss=computedStyle.getPropertyValue("position");
        } else {
            curCss=null;
        }
        if (curCss!=="static" && curCss!=="fixed") {
            t+=element.offsetTop;
        } else if (curCss==="fixed") {
            t+=element.offsetTop;
            break;
        }
        if (typeof(element.parentNode)!=="undefined") {
            element=element.parentNode;
        } else {
            break;
        }
    }
    return t;
}

[Edit] I would advise to use this instead :

var top=elem.getBoundingClientRect().top - document.documentElement.getBoundingClientRect().top

The first function takes not in consideration css transforms, the second one does.

Related