Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do you find the position of an element relative to a parent?

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('.

What is offset parent in jQuery?

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).

What is offset () in jQuery?

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.

What is offset parent?

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;