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.
http://jsfiddle.net/yZGSt/1/
You can calculate the space between your element and bottom of the page by calculating element. offsetTop and window. innerHeight . if you want to calculate space between bottom of your element and bottom of the window then you need to add your element height too.
In JavaScript, you can use the clientHeight property, which returns an element's height, including its vertical padding. Basically, it returns the actual space used by the displayed content. For example, the following code returns 120, which is equal to the original height plus the vertical padding.
The offset() method set or returns the offset coordinates for the selected elements, relative to the document. When used to return the offset: This method returns the offset coordinates of the FIRST matched element. It returns an object with 2 properties; the top and left positions in pixels.
var elDistanceToTop = window.pageYOffset + el.getBoundingClientRect().top
In my experience document.body.scrollTop
doesn't always return the current scroll position (for example if the scrolling actually happens on a different 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With