Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get distance of element relative to its parent element

Tags:

I would like to know how to get the distance/offset/position of an element relative to it's parent element.

Unlike jQuery's position() functionality, which get's the position relative to the parent's offset position, I need to get the (assuming) stable position of an element as it's distance from the top of the containing/parent element.

example:

<div id="parent">
  <div id="pos1">Has a position of 0px from top of containing parent el.</div>
  <br style="height:20px;">
  <br style="height:20px;">
  <div id="pos2">Has a position of 40px from top of containing parent el.</div>
</div>

So, no matter what the position of the parent element to the document, the position of pos1 and pos2 would be reported the same, as they don't change relative to their parent element...

Is this possible?

like image 882
Victor S Avatar asked Jul 04 '12 17:07

Victor S


1 Answers

This should do it:

$('#pos1').offset().top - $('#pos1').parent().offset().top - $('#pos1').parent().scrollTop() 
like image 123
daniloquio Avatar answered Sep 27 '22 15:09

daniloquio