SyntaxStudy
Sign Up
jQuery jQuery Position and Offset
jQuery Intermediate 5 min read

jQuery Position and Offset

Finding where an element sits on the page — or relative to its parent — is a frequent requirement for tooltips, dropdowns, and custom scroll behaviour. jQuery simplifies this with two complementary methods: .offset() and .position().

.offset()

.offset() returns the coordinates of the element relative to the document. The returned object has top and left properties in pixels. You can also use it as a setter by passing an object with new coordinates, which jQuery translates into the appropriate CSS adjustments.

.position()

.position() returns coordinates relative to the element's offset parent (the nearest positioned ancestor). This is the value you need when placing an absolutely-positioned child inside a relatively-positioned container.

  • .offset() — position from document top-left
  • .position() — position from offset parent
  • .scrollTop() / .scrollLeft() — get or set scroll position

Combine .offset() with $(window).scrollTop() to determine whether an element is currently visible in the viewport — a common technique for lazy loading and scroll-triggered animations.

Example
// Get offset from document
var pos = $('#card').offset();
console.log('Top: ' + pos.top + ', Left: ' + pos.left);

// Get position from offset parent
var rel = $('#tooltip').position();
console.log('Relative top: ' + rel.top);

// Set offset (move element)
$('#floater').offset({ top: 100, left: 200 });

// Scroll position
var scrolled = $(window).scrollTop();
console.log('Scrolled: ' + scrolled + 'px');

// Smooth scroll to element
$('html, body').animate({
    scrollTop: $('#section2').offset().top
}, 600);
Pro Tip

Use .offset() for document-relative positioning and .position() when working inside a positioned container.