Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!