Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 701
Som Torroto Avatar asked Aug 10 '11 07:08

Som Torroto


2 Answers

.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>
like image 50
James Avatar answered Oct 19 '22 23:10

James


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

like image 27
Swapnil Navalakha Avatar answered Oct 20 '22 00:10

Swapnil Navalakha