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);
});

Try it yourself

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()

Try it yourself

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:

  • Value pairs, such as {top:100,left:0}
  • Object with top and left properties

Try it yourself

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.

  • index - Optional. Accepts the index position of the selector
  • oldvalue - Optional. Accepts the current coordinates of the selector.

Try it yourself

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.