Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery position() include margin

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

like image 433
user1506145 Avatar asked Jun 29 '15 11:06

user1506145


People also ask

How do I set relative position in jQuery?

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.

What is the difference between position and offset in jQuery?

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.

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 () Top?

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.


1 Answers

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);
like image 166
Philip Dernovoy Avatar answered Oct 16 '22 02:10

Philip Dernovoy