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?
jQuery.offset
needs to be combined withscrollTop
andscrollLeft
as shown in this diagram:Demo:
I found that the answer by cballou was no longer working in Firefox as of Jan. 2014. Specifically,
if (self.pageYOffset)
didn't trigger if the client had scrolled right, but not down - because0
is a falsey number. This went undetected for a while because Firefox supporteddocument.body.scrollLeft
/Top
, but this is no longer working for me (on Firefox 26.0).Here's my modified solution:
Tested and working in FF26, Chrome 31, IE11. Almost certainly works on older versions of all of them.
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.
Here is a function that calculates the current position of an element within the viewport:
The return values are calculated like this:
Usage:
Demo:
Look into the Dimensions plugin, specifically
scrollTop()
/scrollLeft()
. Information can be found at http://api.jquery.com/scrollTop.Here are two functions to get the page height and the scroll amounts (x,y) without the use of the (bloated) dimensions plugin: