Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to find the vertical distance from top in px of an element using jQuery

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!

like image 453
ptamzz Avatar asked Oct 15 '11 14:10

ptamzz


People also ask

How do you get the distance from the top for an element?

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.

How far is the element from the top of the window?

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).

What is offset in JavaScript?

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

Use .offset() to get the distance between an element and the top of the document:

$("li.test").offset().top 
like image 109
Rob W Avatar answered Sep 18 '22 18:09

Rob W