Alex Rivera | Logout

Using jquery to get element's position relative to viewport

Asked 2009-10-14T16:05:49.803
120

What's the proper way to get the position of an element on the page relative to the viewport (rather than the document). jQuery.offset function seemed promising:

Get the current coordinates of the first element, or set the coordinates of every element, in the set of matched elements, relative to the document.

But that's relative to the document. Is there an equivalent method that returns offsets relative to the viewport?

Edit
Report

2 Answers

294

The easiest way to determine the size and position of an element is to call its getBoundingClientRect() method. This method returns element positions in viewport coordinates. It expects no arguments and returns an object with properties left, right, top, and bottom. The left and top properties give the X and Y coordinates of the upper-left corner of the element and the right and bottom properties give the coordinates of the lower-right corner.

element.getBoundingClientRect(); // Get position in viewport coordinates

Supported everywhere.

answered 2013-03-01T09:39:54.620
27

Look into the Dimensions plugin, specifically scrollTop()/scrollLeft(). Information can be found at http://api.jquery.com/scrollTop.

answered 2009-10-14T16:14:09.617

Your Answer