6

Question: What is the difference between .offset() and .position()?

I read some docs on that but still I am not at all clear with what is real difference between these two. I would request a simple explanation on the same.

My Observation:

I wrote a javascript code which I placed in the web page(.aspx) itself. The javascript is basically setting the position of a modal popup. In that code I used .position() to get the position of a div where i will be placing the modal popup. Now, Here is the twist- When I moved the javascript code into a seperate js file, The .position() was not at all properly working instead I used .offset() and It was working fine.

I would request an explaination on this ?

Bose_geek
  • 498
  • 5
  • 18
  • possible duplicate of [jQuery: Difference between position() and offset()](http://stackoverflow.com/questions/3202008/jquery-difference-between-position-and-offset) – user Mar 17 '14 at 11:42

1 Answers1

7

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.

Hope it makes sense.

vipulsharma
  • 1,242
  • 1
  • 8
  • 16
  • What is the "offset parent"? Is that the first ancestor with a position style attribute set to anything other than static? – Hubro Aug 08 '13 at 05:18
  • 1
    yes, the offset parent is the closest positioned parent other than static. – vipulsharma Aug 08 '13 at 05:20
  • The .position() always refers to the parent element's coordinates, while the .offset() may calculate such coordinates by taking into account the offset of the parent from the whole page when this element is positioned. Correct me if I am wrong ? – Bose_geek Aug 08 '13 at 05:27
  • I guess explaination on my observation is still pending ? – Bose_geek Aug 08 '13 at 06:28
  • 1
    Copied and pasted the answer from the stackover flow [answer](http://stackoverflow.com/questions/3202008/jquery-difference-between-position-and-offset) – Benjamin Aug 28 '14 at 10:46