What Does the jQuery offset() Method Return?
This article provides an overview of the jQuery offset()
method, explaining the exact data structure it returns, how its
coordinate system works, and how it handles different element
selections. You will learn the specific properties of the returned
object, what the coordinate values represent, and how
offset() differs from related positioning methods in
jQuery.
When called as a getter, the jQuery offset() method
returns a plain JavaScript object containing two numeric properties:
top and left. These properties represent the
current pixel coordinates of an HTML element relative to the entire
document.
The structure of the returned object looks like this:
{
top: 150,
left: 300
}Both top and left are numbers (floats or
integers) representing distance in pixels. Unlike CSS property values
retrieved with the .css() method, these values do not
include the "px" unit string.
Key Characteristics of the Returned Object
- Relative to the Document: The coordinates are
calculated relative to the document root, not the viewport or the
element's parent container. This means scrolling the page does not
change the values returned by
offset(), because the element's position relative to the document boundary remains the same. - First Element Only: If the jQuery selector matches
multiple elements, the
offset()method returns the coordinates of only the first element in the matched set. - Empty Selections: If the selector does not match
any elements (e.g.,
$('#nonexistent').offset()), the method returnsundefined. - Hidden Elements: The
offset()method cannot reliably retrieve coordinates for elements hidden withdisplay: noneor elements that are not part of the DOM. In modern jQuery versions, callingoffset()on such elements may return{ top: 0, left: 0 }or produce inaccurate measurements.
Difference Between offset() and position()
While offset() returns coordinates relative to the
document, the related jQuery method position() returns an
object with top and left properties relative
to the element's closest positioned ancestor (an offset parent with CSS
positioning set to relative, absolute, or
fixed). Use offset() when you need global page
coordinates, such as when placing custom tooltips, overlays, or
drag-and-drop elements.