jQuery Introduction | Element Dimensions | Element Position .offset() .position()
Element Position
jQuery provides methods that make it easy to return and set the position of a selected element.
| Method | Description |
|---|---|
| .offset() | Returns the position of the first element in the selected set relative to the HTML document, or sets the position of the selected element to the value passed as an argument. |
| .position() | Returns the relative position of the first element in the selected set based on the parent element that served as the reference when the element was positioned on the web page. |
.offset() Method
The .offset() method returns or sets the offset coordinates of the selected element relative to the HTML document.
The following example returns the position of the selected element.
$("button").on("click", function(){
var p = $("p:first").offset();
$("span").text("top: " + p.top + "px, left: " + p.left + "px");
});
The following example sets the position of the selected element.
$("button").on("click", function(){
$("p").offset({ top: 200, left: 10 });
var p = $("p:first").offset();
$("span").text("top: " + p.top + "px, left: " + p.left + "px");
});
.position() Method
Unlike .offset(), the .position() method returns the relative position of the selected element based on the parent element, or offset parent, that served as the reference when it was positioned on the web page.
The following example returns and displays the position from .position() and .offset() at the same time.
$("button").on("click", function(){
var p = $("p").position();
$("#position").text("position - top: " + p.top + "px, left: " + p.left + "px");
var o = $("p").offset();
$("#offset").text("offset - top: " + o.top + "px, left: " + o.left + "px");
});
Difference Between .offset() and .position()
The differences between .offset() and .position() are as follows.
| Method Name | Description |
|---|---|
| .offset() method | Uses the HTML document as the reference. |
| .position() method | Uses the parent element that serves as the reference for positioning the selected element on the web page. |