jQuery CSS Operation - offset() Method
Example
Get the current offset of the <p> element:
$(".btn1").click(function(){ x=$("p").offset(); $("#span1").text(x.left); $("#span2").text(x.top); });
Definition and Usage
The offset() method returns or sets the offset (position) of the matching element relative to the document.
Returns offset coordinates
Returns the offset coordinates of the first matching element.
The object returned by this method contains two integer properties: top and left, in pixels. This method is only valid for visible elements.
Syntax
$(selector).offset()
Sets offset coordinates
Sets the offset coordinates of all matching elements.
Syntax
$(selector).offset(value)
Parameters | Description |
---|---|
value |
Required. Specifies the top and left coordinates in pixels. Possible values:
|
Use a function to set offset coordinates
Use a function to set the offset coordinates of all matching elements.
Syntax
$(selector).offset(function(index,oldoffset))
Parameters | Description |
---|---|
function(index,oldoffset) |
Specifies a function that returns the new offset coordinates of the selected elements.
|
More examples
- Use an object to set a new offset value for an object.
- Use the coordinates in the new object to locate the element.
- Use the position of another element to set a new offset value for the element.
- Use the position of an existing object to locate an element.