Calculate element position

I would like to calculate the vertical position of a <div> using jQuery.

How can I do it?

Here is an illustration that describes what I mean:

enter image description here

+6
source share
5 answers

I think you are looking for its offset from the top of the page, right?

 $('#div').scrollTop(); 

If this is not the case, perhaps the offset will work:

 $('#div').offset().top; 

Ok , now that it should be relative to the parent, try the following:

 $('#div').position().top; 
+10
source
 $('#innerDiv').position() 

Get the current coordinates of the first element in the set of matched elements, relative to the parent offset .

jQuery Guide for Position ()

+2
source

I think you are looking

 $(elem).offset(); 

http://api.jquery.com/offset/

If you want this to be relative to the container, you are instead of http://api.jquery.com/position/ .

+1
source

jQuery has several features to help you find the offset you are looking for.

 var element = $("#your_element"); // Get the current coordinates of the first element in the set of matched elements, relative to the document. element.offset() // Get the closest ancestor element that is positioned. element.offsetParent() // Get the current coordinates of the first element in the set of matched elements, relative to the offset parent. element.position() // Get the current horizontal position of the scroll bar for the first element in the set of matched elements. element.scrollLeft() // Get the current vertical position of the scroll bar for the first element in the set of matched elements. element.scrollTop() 

Read more about this on the jQuery offset api page.

+1
source

I believe that the jQuery API "position ()" is not what you are looking for, as it is defined as the "current position of the element relative to the offset parent" (basically this corresponds to element.offsetTop)

Therefore, if you want the top position of an element to relate to its parent (not necessarily the offset parent), use this instead:

 var top = (element.parentNode == element.offsetParent) ? element.offsetTop : element.offsetTop - element.parentNode.offsetTop; 
0
source

Source: https://habr.com/ru/post/886405/


All Articles