Som Torroto
Som Torroto

Reputation: 51

jQuery's problem with the position method

If I have the following markup:

<div id="parent" style="width: 300px; height: 300px;">
  <div id="child" style="position: relative; left: 0; top: 0; width: 100px; height: 100px;"></div>
</div>

and I want to get the position of the child relative to its parent, would the only way be as follows?:

x = parseInt($('#child').css('left')); // returns 0 as needed
y = parseInt($('#child').css('top')); // return 0 as needed

Because if I do the following:

x = $('#child').position().left; // most likely will not return 0 
y = $('#child').position().top; // most likely will not return 0

the position is wrong due to the fact that the offset method does also add the margin, padding, and border of the grandparents (be it the body element with its default margins or any other grandparent element).

I need to get the right position (in my example it would be 0, 0) but I suspect there is no method in jQuery that can calculate it for me?

Upvotes: 5

Views: 5708

Answers (2)

Swapnil Navalakha
Swapnil Navalakha

Reputation: 319

The .position() method allows us to retrieve the current position of an element relative to the offset parent. Contrast this with .offset(), which retrieves the current position relative to the document. Use .offset()

Upvotes: 5

James
James

Reputation: 111870

.position() is correct. It'll give you the x and y values relative to an element's offset parent. Your #child element is positioned relative to its own offset parent, which is <body>. In order to make #parent its offset parent, give it a position of relative or absolute.

<div id="parent" style="position: relative; width: 300px; height: 300px;">
    <div id="child" style="position: relative; left: 0; top: 0;...;"></div>
</div>

Upvotes: 7

Related Questions