I want to know how to use JavaScript to get the distance of an element from the top of the page not the parent element.
I want to know how to use JavaScript to get the distance of an element from the top of the page not the parent element.
offsetTop only looks at the element's parent. Just loop through parent nodes until you run out of parents and add up their offsets.
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 };
}
UPDATE: This answer has some problems, values will have tiny differences compare to what it should be and will not work correctly in some cases.
Check @eeglbalazs's answer, which is accurate.