I am trying to get the top offset of a div, and I have the following code that gets run when the page gets scrolled:
var $elem = document.querySelector(selector);
var elemTop = $elem.offsetTop;
console.log(elemTop);
But when I scroll it always prints 0
to the console, even though the element is below the fold.
The offsetTop property returns the top position (in pixels) relative to the parent. The returned value includes: the top position, and margin of the element. the top padding, scrollbar and border of the parent.
The HTMLElement. offsetTop read-only property returns the distance of the outer border of the current element relative to the inner border of the top of the offsetParent , the closest positioned ancestor element.
The correct approach is to use element. getBoundingClientRect() to Get absolute position of element in JavaScript. Use element id to get its position in the browser window.
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 elmTop = $elem.getBoundingClientRect().top + window.scrollY;
element.getBoundingClientRect() gives the position within the viewport, and window.scrollY gives the distance from the top of the viewport to the top of the document.
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