What is the difference between offset and position in jQuery?
The jQuery offset() method, and jQuery position() method are similar in nature. Both of the methods can be applied to visible elements, and both return the object that contains the integer co-ordinate properties, top and left.
Although both methods have some similarities, but the jQuery offset() method is different from the jQuery position() method. The offset() method retrieves the current position relative to the document, whereas the position() method retrieves the current position of an element relative to the parent element.
Before going to the difference, let’s first discuss about both jQuery methods.
jQuery offset() method
The jQuery offset() method is used to get the current offset of the first matched element relative to the document. It is generally used in drag-and-drop functions. The offset() method provides two methods: to set or return the offset co-ordinates for the selected elements relative to the document.
To return the offset: When this method is used to return the offset, it returns the offset co-ordinates of the FIRST matched element.
To set the offset: When this method is used to set the offset, it sets the offset co-ordinates of ALL matched elements.
jQuery position() method
The jQuery position() method allows us to retrieve the current position of an element relative to the parent element. It returns the position of the first matched element. This method returns the object with two properties: top and left position in pixels.
The position() method is more useful when we have to position a new element near another one within the same containing the DOM element.
jQuery offset() v/s jQuery position()
offset() method | position() method |
---|---|
It is relative to the document. | It is relative to the parent. |
This method is recommended to use when we have to position a new element on top of an already existing element. | It should be used when we have to position a new element near another one. |
It returns the current position of an element relative to the document. | It returns the current position relative to the parent. |
Now, let’s see an example of using the position() method and offset() method simultaneously.
Example
In this example, we are applying the position() and offset() method to the given h2 element for finding the position and offset of it. There are two buttons named as Position and Offset that returns the top and left co-ordinates value of the h2 element correspondingly.
The position() method gives the coordinates relative to the parent, and the offset() method provides the coordinates relative to the document.
Output
After the execution of the above code, the output will be –
On clicking the Position button, the output will be –
On clicking the offset button, the output will be –