Description:
The offset method will Get the current coordinates of the element for the matched elements, relative to the document. It provides two methods which will set/Get the offset co-ordinates for the selected elements.
Get offset: It will returns the offset co-ordinates of the matched element.
Set offset: It will sets the offset co-ordinates of matched elements.
Syntax
- GET : $(selector).offset()
- SET :$(selector).offset({top:value,left:value}) ,ย $(selector).offset(function(index, currentcoordinates))
top:value,left:value | It specifies the top and left co-ordinates in pixels for SET. |
Function (index,Currentcoordinates) | It specifies a function that returns an object containing the top and left coordinates.
Index: It Get the index position for the selected element. Currentcoordinates: It returns the current coordinates of the selected element.The function should return an object with the new top and left properties. |
Difference between postion() and offset():
The .position() method allows us to retrieve the current position of an element relative to the parent.ย But theย .offset() method allows us to retrieve the current position of an element relative to the document.
Example:ย
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script> <style> .defaultClass { border: 5px solid #eed5b7; padding: 10px; width: 80px; height: 80px; background-color: #1a80b6; display: inline-block; } </style> <script type="text/javascript"> $(document).ready(function () { $('.btnClass').click(function () { var divBoxDetail = $("#divBoxDetails"); var offsetPosition = divBoxDetail.offset(); divBoxDetail.text("offset left: " + Math.round(offsetPosition.left) + ", offset top: " + Math.round(offsetPosition.top)); }) }); </script> </head> <body> <button class="btnClass" id="addMethod">GEt Offset Position</button><br/><br /> <div id="divbox1" class="defaultClass"> </div> <br /><br /> <div id="divBoxDetails"></div> </body> </html> |
Output:ย
Leave A Comment