To get the offset position of an HTML element relative to its parent, you can use the offsetLeft and offsetTop properties of the element. Here is example: const div = document. querySelector('.
The offsetParent() method returns the first positioned parent element. Tip: An element can be positioned with jQuery, or with the CSS position property (relative, absolute, or fixed).
jQuery offset() Method 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.
The offset parent is the nearest ancestor that has a position other than static. If no offset parent exists, the offset parent is the document body.
Use the position() method.
$('#bar').position().left;
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;
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.
offsetLeft = $('#bar').position().left;
offsetTop = $('#bar').position().top;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With