The offset() method in JQuery is used to get and set the offset position of an HTML element.
Say, you want to get the exact position of the <p> element. And the offset() method helps us to get that.
The offset() method has two properties, top and left. The top property tells us the position of the <p> element from the top(In pixels) and the left element tells us the position of the <p> element from the left(In pixels).
Let us see how offset() method acts as a getter method.
<html> <head> <title> My First Programme </title> <script src = "https://cdnjs.cloudflare.com/ajax/libs/JQUERY/3.3.1/jquery.min.js"> </script> </head> <body> <h1> JQuery </h1> <p> Hello World </p> <button> Click it </button> <script> $('button').click( function() { var x = $('p').offset(); alert("The offset value of p element is, top : "+x.top+" and from left : "+x.left); }); </script> </body> </html>
So, if we look at the above code, we have a <p> element.
<p> Hello World </p>
And we have a <button> element,
<button> Click it </button>
And on button click, the JQuery statement gets triggered,
$('button').click( function() { var x = $('p').offset(); alert("The offset value of p element is, top : "+x.top+" and from left : "+x.left); });
So, what we have done is, invoked the offset() method on the <p> element. And stored it in a variable x,
var x = $('p').offset();
And an alert is generated,
alert("The offset value of p element is, top : "+x.top+" and from left : "+x.left);
Now, if we see the output (i.e. The alert),
You get the position of the <p> element in pixels. Where x.top and x.left is used to get the value of top and left from the offset() method.
<html> <head> <title> My First Programme </title> <script src = "https://cdnjs.cloudflare.com/ajax/libs/JQUERY/3.3.1/jquery.min.js"> </script> </head> <body> <h1> JQuery </h1> <p> Hello World </p> <button> Click it </button> <script> $('button').click(function(){ $('p').offset({top: 150, left: 50}); }); </script> </body> </html>
So, if we look at the above code, we have a <p> element.
<p> Hello World </p>
And we have a <button> element,
<button> Click it </button>
And on button click, the JQuery statement gets triggered,
$('button').click( function() { $('p').offset({top: 150, left: 50}); });
And the offset() method is used to set the left and top property of the <p> element.
$('p').offset({top: 150, left: 50});
Now, if we see the output, the <p> element is placed at a position that is 150 pixels away from the top and 50 pixels away from the left.