views:

52

answers:

2

What is the difference between position() and offset()? I tried to do the following in a click event:

console.info($(this).position(), $(this).offset());

And they seem to return exactly the same... (The clicked element is within a table cell in a table)

+3  A: 

The .offset() method allows us to retrieve the current position of an element relative to the document. Contrast this with .position(), which retrieves the current position relative to the offset parent. When positioning a new element on top of an existing one for global manipulation (in particular, for implementing drag-and-drop), .offset() is the more useful.

Source: http://api.jquery.com/offset/

jAndy
+2  A: 

That depends on what context the element is in. position returns the position relative to the offset parent, and offset does the same relative to the document. Obviously, if the document is the offset parent, which is often the case, these will be identical.

If you have a layout like this, however:

 <div style="position: absolute; top: 200; left: 200;">
     <div id="sub"></div>
 </div>

Then the offset for sub will be 200:200, but its position will be 0:0.

David Hedlund
So the offset parent is the first parent with position set to absolute? or?
Svish
@Svish: whoa, did I really miss the code indent? thaks for the edit. yes, the offset parent is the closest *positioned* parent. that is, an element with position set to absolute, relative or fixed (but not static). this is not a jQuery or even a javascript thing, you have the same behavior in css: if you were to give `sub` absolute positioning to 0:0, then it will be in the top left corner of the offset parent.
David Hedlund
Awesome, then it totally makes sense! (No problem with the edit, hehe. I do it all the time :p)
Svish