The jQuery offset() method can be used to return or set the offset the coordinates of the selected element. An offset is the position of the element from the top and left of the screen. You can find or change these positions by using this method.
Syntax
The syntax of this method is given below:-
Description of the Parameters
The description of the parameters are given below.
Parameter Name | Description |
---|---|
selector | You have to select the element using a selector to return or sets the offset coordinates. Use the tag name, class name, or id of the elements to select. |
value | Specify the top or left value to set the offset of the selected element. Its value can be in px, em, etc. |
index | It returns the index position of the selected element. |
current_offset | Returns the current offset coordinates of the selected element. |
jQuery offset() Method to Get or Return the Offset Coordinates
If you want to find the offset position of the element, you can use this method. You have to first select the element to get or return its offset coordinates. See the example given below to get the offset coordinates of the element.
Example
1 2 3 4 5 6 7 8 9 10 |
<script> $(document).ready(function(){ $('.mygetbtn').click(function(){ var myoffset = $(".mypara").offset(); alert("Left coordinate is: "+myoffset.left+", Top coordinate is:"+myoffset.top); }); }); </script> <button type="button" class="mygetbtn">Click to Return Offset Coordinates</button><br><br> <p class="mypara">This is my paragraph.</p> |
Output
This is my paragraph.
You have to click the button given above to get the offset coordinates of the selected element. It displays the offset position values in the alert box. It’s useful when you want to get the position of the element.
How to Set the Offset Coordinates
You can also set the offset coordinates of the selected element. Specify the coordinate values as the parameter of the jQuery offset() method. See the example given below to use the method.
Example
1 2 3 4 5 6 7 8 9 |
<script> $(document).ready(function(){ $('.mysetbtn').click(function(){ $(".mysetpara").offset({top:200, left:400}); }); }); </script> <button type="button" class="mysetbtn">Click to Set Offset Coordinates</button><br><br> <p class="mysetpara">This is my paragraph.</p> |
Output
This is my paragraph.
You have to click the button given above to set the offset coordinates of the selected element. You can find the difference when you click the button.
You may also like to read
I hope you like this tutorial on jQuery offset() method. If you have any queries regarding the tutorial, please comment below.
References