How do I find the vertical distance from the top of the page to where the element exist in the DOM using javascript/jQuery?
I've something like
<ul> <li>one</li> <li>one</li> <li>one</li> <li>one</li> <li class="test">one</li> .... .... .... <li>one</li> </ul>
For example here, I want to find the vertical distance from top of the page to the li#test
element.
I tried .scrollTop()
but it always comes as 0!
To get the distance from the top for an element with JavaScript, we get the sum of the window. pageYOffset property and the element's top value. const elDistanceToTop = window. pageYOffset + el.
You can use . offset() to get the offset compared to the document element and then use the scrollTop property of the window element to find how far down the page the user has scrolled: var scrollTop = $(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.
Use .offset()
to get the distance between an element and the top of the document:
$("li.test").offset().top
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