3 examples of jQuery offset method with top and left

They offset method of jQuery

The jQuery offset method is used to get the position or coordinates of the given element. The offset method is also used to set the coordinates of all matched elements. The coordinates are relative to the document while the values are in pixels.

An example of offset method

If you require to get or set coordinates according to offset parent then use jQuery $.position method.

Note that, if there are more than one matched elements found to get coordinates, the offset method will return only first matched element coordinates.

If you are setting coordinates by using offset method, then it will set coordinates for all matched elements.

Following are a few examples to make it easier to understand, but let us first look at the syntax of offset method.

Syntax of jQuery offset()

The basic syntax to get coordinates:


The syntax to set coordinates:


See simple examples below to see how to use offset method.

Example of getting coordinates with offset jQuery method

The example below uses div element to return its coordinates by using offset method of jQuery.

jQuery offset get

Experience this example online

Example of div with CSS style applied

This example uses the same div as above, with CSS applied that adds margin from top and left and then returns div coordinates as you click on the button.

jQuery offset

Experience this example online

Setting coordinates by offset method

The following example shows how to set coordinates by using offset method. As you click on the button to set coordinates, it will set top to 20px and left to 30px.

Experience this example online


Further reading: jQuery position