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.
Asked
Active
Viewed 504 times
2
-
You haven't showed what you have tried so far which I always recommend. So you know the distance from the top of the viewport. What should you do next? Your search should have found this answer https://stackoverflow.com/questions/34422189/get-item-offset-from-the-top-of-page – Djave Feb 06 '22 at 19:24
-
1Does this answer your question? [Get item offset from the top of page](https://stackoverflow.com/questions/34422189/get-item-offset-from-the-top-of-page) – Djave Feb 06 '22 at 19:27
1 Answers
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.

Fabien Auréjac
- 167
- 8
-
1This is overkill and hard to read compared to something like `elem.getBoundingClientRect().top + window.scrollY` – Djave Feb 06 '22 at 19:26
-
Yes totally agree ! I should have answered this kind of advice. I took too literally the question. – Fabien Auréjac Feb 06 '22 at 19:34
-
but then if you set for example margins or top to the document element which is not common I agree, you can get wrong values with elem.getBoundingClientRect().top + window.scrollY then you'll have to do elem.getBoundingClientRect().top - document.documentElement.getBoundingClientRect().top – Fabien Auréjac Feb 06 '22 at 19:43