Difference between .position () and .offset () and interesting observation?

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

I have read some documents about this, but still I do not quite understand what the real difference between the two is. I would ask for a simple explanation on this.

My observation:

I wrote javascript code that I posted on the webpage itself (.aspx). Javascript basically sets the position of a modal popup. In this code, I used .position () to get the div position where I will place the modal popup. Now here's a twist . When I moved the javascript code to a separate js file, The.position () did not work properly, I used .offset () instead, and it worked fine.

I would ask to explain about this?

+6
source share
1 answer

It depends on the context in which the element is located. position returns the position relative to the parent of the offset, and the offset does the same for the document. Obviously, if the document is the parent of the offset, which often happens, they will be identical.

If you have a layout like this:

<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 this makes sense.

+7
source

Source: https://habr.com/ru/post/951269/


All Articles