// To get offset
$(selector).offset();
// To set offset
$(selector).offset({top:value,left:value});
// To callback
$(selector).offset(function(index, offset));
Parameter Values
Value
Type
Explanation
{top:value,left:value}
Optional
Specifies an object containing the properties top and left, which are numbers indicating the new top and left coordinates for the elements.
function(index, offset)
Optional
Specifies a function to return the coordinates to set. Parameters Explanation
index - Returns the index position of the element in the set.
offset - Returns the current coordinates of the selected element.
Set Offset
In the following example, we will set the offset value of the paragraph (first matched) to 200px (both top and left), relative to its parent element.
Example
HTML Editor
<!DOCTYPE html>
<htmllang="en-US">
<head>
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<h1>jQuery offset() Method</h1>
<p>Try to click on the button</p>
<button>Click Me</button>
<script>
$(document).ready(function(){
$("button").click(function(){
varx= $("p").offset({
top : 200,
left: 200 });
});
});
</script>
</body>
</html>