How to Set Element Coordinates Using jQuery offset()
The jQuery .offset() method allows developers to both
retrieve and set the current coordinates of any DOM element relative to
the document. While frequently used as a getter, passing an object with
coordinate values converts the method into a setter that automatically
repositions the selected element. This article explains how to use
.offset() to set an element's position, the correct syntax
required, how to use callback functions for dynamic positioning, and
essential positioning behaviors to keep in mind.
Basic Syntax for Setting Coordinates
To set the document coordinates of an element, pass a plain
JavaScript object containing the top and left
properties to the .offset() method:
$("#myElement").offset({ top: 150, left: 300 });In this example, #myElement will be repositioned so its
top-left corner sits precisely 150 pixels from the top of the document
and 300 pixels from the left edge of the document.
How jQuery Handles Positioning
When setting coordinates using .offset(), jQuery
computes the difference between the element's current document position
and the target coordinates. It then updates the element's CSS
top and left properties accordingly.
Key technical behaviors include:
- Position Property: If the element currently has a
CSS
positionofstatic, jQuery will automatically change it torelativeso thetopandleftCSS properties take effect. - Scroll Position: Because coordinates are calculated relative to the entire document—not the viewport—the element will stay aligned to the document coordinates regardless of whether the page is currently scrolled.
Setting Coordinates Using a Callback Function
jQuery also supports passing a callback function to
.offset(). This is useful when calculating new positions
based on the element's existing coordinates or its index in a
collection:
$(".box").offset(function(index, currentCoordinates) {
return {
top: currentCoordinates.top + 20,
left: currentCoordinates.left + (index * 50)
};
});The callback function accepts two arguments:
index: The zero-based index position of the element within the jQuery collection.currentCoordinates: An object containing the element's current{ top, left }document coordinates.
The function must return an object with the new top and
left numerical values.
.offset() vs.
.position()
It is important not to confuse .offset() with
.position():
.offset()measures and sets coordinates relative to the document. It functions as both a getter and a setter..position()measures coordinates relative to the element's offset parent (the closest positioned ancestor). It is strictly a getter and cannot be used to set positions.