Last Updated: October 04, 2020
·
47.41K
· artchang

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:

fatal: refusing to merge unrelated histories

1 Response
Add your response

Brilliant!

over 1 year ago ·

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside