How to get offset() relative to parent in jQuery?

JavascriptJquery

Javascript Problem Overview


This gives me the position of some element from the left edge of the main window:

$('#bar').offset().left;

If that element is situated inside some other element and I wanted the position of #bar relative to #foo (it's parent), how can I get that?

<style>
#foo { width: 200px; margin: 0 auto; }
#foo #bar { width: 50px; margin: 0 auto; }
</style>

<div id="foo">
   <span id="bar"></span>
</div>

I saw that there is a function called offsetParent() but when console logged it doesn't seem like this function has any properties called left or x. So not sure if that can be used to get what I need.

So in my example above the offset should be something around 125px from the parent's edge rather than some thousands of pixels from the main windows edge.

Javascript Solutions


Solution 1 - Javascript

Use the position() method.

$('#bar').position().left;

Solution 2 - Javascript

It's simple enough: get the offset of the element and substract the offset of its parent.

var elem = $("#bar");
var offset = elem.offset().left - elem.parent().offset().left;

Solution 3 - Javascript

Position within a div relative to its parent:

In my case, when scroll changed the calculated offset also changed and it shouldn't so i ended up using pure javascript which is quicker anyway...

element.get(0).offsetTop

Other variation like Left is also possible element.get(0).offsetLeft

Conclusion

element.offset().top or position() are not optimal for position relative cases.

Solution 4 - Javascript

offsetLeft = $('#bar').position().left;
offsetTop = $('#bar').position().top;

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
Questionuser967451View Question on Stackoverflow
Solution 1 - JavascriptScorpion-PrinceView Answer on Stackoverflow
Solution 2 - JavascriptNiet the Dark AbsolView Answer on Stackoverflow
Solution 3 - JavascriptMiguelView Answer on Stackoverflow
Solution 4 - JavascriptMax SnijdersView Answer on Stackoverflow