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

JavascriptJquery

Javascript Problem Overview


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!

Javascript Solutions


Solution 1 - Javascript

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

$("li.test").offset().top

Solution 2 - Javascript

Rob W's answer is correct - that will give you the offset from the top of the full page.

If you want to get the offset from the top of the viewable screen, you should do this:

var viewableOffset = $("#li.test").offset().top - $(window).scrollTop();

Hope that helps!

Solution 3 - Javascript

As far as i know .offset() get the distance between the current scroll position and the top of the document.

You need to use this: $("li.test").position().top

Solution 4 - Javascript

Use $(element).offset().top and add height of existing fixed elements on the page to it to make it more accurate.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionptamzzView Question on Stackoverflow
Solution 1 - JavascriptRob WView Answer on Stackoverflow
Solution 2 - JavascriptthexfactorView Answer on Stackoverflow
Solution 3 - JavascriptCrisan Raluca TeodoraView Answer on Stackoverflow
Solution 4 - Javascriptrut shahView Answer on Stackoverflow