Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between .position() and .offset() and an interesting Observation?

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 ?

like image 357
Bose_geek Avatar asked Aug 08 '13 05:08

Bose_geek


1 Answers

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.

like image 196
vipulsharma Avatar answered Oct 15 '22 00:10

vipulsharma