Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get item offset from the top of page

Tags:

javascript

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.

like image 244
Get Off My Lawn Avatar asked Dec 22 '15 18:12

Get Off My Lawn


People also ask

How do you find the offset of a top?

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.

What is offset () Top?

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.

How do I get the position of an element on my screen?

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.

What is offset () top in jQuery?

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.


1 Answers

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.

like image 200
Jack Avatar answered Oct 06 '22 08:10

Jack