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.
Related protips:
Written by Arthur Chang
Related protips
1 Response
Brilliant!
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Jquery
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#