If I want to include the margin when measuring the width of an element I may call element.outerWidth(true);
However, I can't find a similar way to get the left offset of an element in a container, where the margin is included. element.position().left
doesn't include margin.
I've tried element[0].getBoundingClientRect().left
, and that works but is there a similar jquery call?
EDIT: It seems that the native javascript call above doesn't give me the margin either..
jQuery position() MethodThe position() method returns the position (relative to its parent element) of the first matched element. This method returns an object with 2 properties; the top and left positions in pixels.
Although both methods have some similarities, but the jQuery offset() method is different from the jQuery position() method. The offset() method retrieves the current position relative to the document, whereas the position() method retrieves the current position of an element relative to the parent element.
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 offsetTop property returns the top position (in pixels) relative to the parent. The returned value includes: the top position, and margin of the element.
This is a limitation of jQuery's .position(), which has this limitation:
Note: jQuery does not support getting the position coordinates of hidden elements or accounting for borders, margins, or padding set on the body element.
Recommended solution:
var position = $element.position();
x = position.left + parseInt($element.css('marginLeft'), 10);
y = position.top + parseInt($element.css('marginTop'), 10);
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