jQuery - Positioning in jQuery with .offset() and .position()
1. .offset()
-
Returns (or sets) the coordinates of an element relative to the entire document (top-left corner of the page).
-
Useful when you want to know where an element is placed on the page, regardless of parent containers.
Example:
var pos = $("#box").offset();
console.log("Top: " + pos.top + ", Left: " + pos.left);
Output (for example):
Top: 150, Left: 200
-
You can also set position:
$("#box").offset({ top: 300, left: 400 });
2. .position()
-
Returns the coordinates of an element relative to its offset parent (the nearest positioned ancestor).
-
Doesn’t count margins, only considers padding/border of the parent.
Example:
var pos = $("#box").position();
console.log("Top: " + pos.top + ", Left: " + pos.left);
Output (for example):
Top: 20, Left: 50
Key Difference
Method | Position Relative To | Example Use |
---|---|---|
.offset() |
Entire document (page) | Useful for placing tooltips, modals, or tracking scroll position. |
.position() |
Nearest positioned parent (offset parent) | Useful when positioning elements inside a container. |
Illustration
Imagine a #box
inside a #container
:
Document (0,0) ──────────────► offset() (absolute page coords)
┌───────────────────────┐
│ #container │
│ (positioned parent) │
│ ┌───────────────┐ │
│ │ #box │ │
│ │ position() │ │
│ └───────────────┘ │
└───────────────────────┘