Position of Div in relation to the Top of the Viewport

PF1 picture PF1 · Dec 25, 2009 · Viewed 35.5k times · Source

I am wondering how I can get the number of pixels (or measurement in general) from a div to the top of the window in Javascript. I am not looking for an offset y in relation to the document, simply to the top of where the browser is displaying. I tried the "answered" solution here: Is it possible to get the position of div within the browser viewport? Not within the document. Within the window, but at least in Safari, I am running into a problem where it returns the same number no matter where the div's really are.

Thanks for any help!

Answer

Himanshu P picture Himanshu P · Sep 13, 2013

The existing answers are now outdated. The getBoundingClientRect() method has been around for quite a while now, and does exactly what this question asks for. Plus it is supported across all browsers.

From this MDN page:

The returned value is a TextRectangle object, which contains read-only left, top, right and bottom properties describing the border-box, in pixels, with the top-left relative to the top-left of the viewport.

You use it like so:

var viewportOffset = el.getBoundingClientRect();
// these are relative to the viewport
var top = viewportOffset.top;
var left = viewportOffset.left;