a2spaq
Last Updated: February 25, 2016
·
16.85K
· artchang
Photo sep 26  14 31 57

jQuery offset of element in relation to viewport

jQuery's .offset() method is pretty close to what we want, except it gets the offset coordinates for an object in relation to the whole document. What we'd want is to couple this with the .scrollTop() and .scrollLeft() methods.

.scrollTop() will give you the number of pixels scrolled from the top of an object, so you basically want to take the difference of the scrollTop of the document and the actual offset top coordinate to get the viewport top offset.

coffeescript example:

photo = $('#photo')
offset = photo.offset()
photoViewportOffsetTop = offset.top - $(document).scrollTop()
photoViewportOffsetLeft = offset.left - $(document).scrollLeft()

$(document).scrollTop()

Make sure you use $(document) as the object you're looking for the scrollTop() or scrollLeft() for, rather than the object itself, because the object might not be scrolled out of the frame. You want the offset of the viewport scrolled away from the document.

1 Response
Add your response

5007
8b8731cc8fc06877833590f617792af8

Brilliant!

over 1 year ago ·