Tutorials References Menu

jQuery offset() Method

❮ jQuery HTML/CSS Methods

Example

Return the offset coordinates of a <p> element:

$("button").click(function(){
  var x = $("p").offset();
  alert("Top: " + x.top + " Left: " + x.left);
});
Try it Yourself »

Definition and Usage

The offset() method set or returns the offset coordinates for the selected elements, relative to the document.

When used to return the offset:
This method returns the offset coordinates of the FIRST matched element. It returns an object with 2 properties; the top and left positions in pixels.

When used to set the offset:
This method sets the offset coordinates of ALL matched elements.


Syntax

Return the offset coordinates:

$(selector).offset()

Set the offset coordinates:

$(selector).offset({top:value,left:value})

Set offset coordinates using a function:

$(selector).offset(function(index,currentoffset))

Parameter Description
{top:value,left:value} Required when setting the offset. Specifies the top and left coordinates in pixels.

Possible values:
  • Name/Value pairs, like {top:100,left:100}
  • An object with top and left properties (example)
function(index,currentoffset) Optional. Specifies a function that returns an object containing the top and left coordinates
  • index - Returns the index position of the element in the set
  • currentoffset - Returns the current coordinates of the selected element

Try it Yourself - Examples

Set the offset coordinates
How to set the offset coordinates of an element.

Set offset coordinates using a function
Using a function to set the offset coordinates of an element.

Set the offset coordinates for an element using an object
How to set the offset coordinates for an element using a new object.

Set the offset coordinates for an element using the offset coordinates of another element
How to set the offset coords for an element using the offset coords of an existing element.


❮ jQuery HTML/CSS Methods