Reputation: 263
So I'm trying to perform some calculations via javascript / jquery in order to make elements in my webapp responsive. I understand that by using object.offset().top
I'm able to obtain the number of pixels between the top of my content and the top of the object. However, part of my design is that certain elements stick to the top of the screen while the rest of it scrolls past, and then object.offset().top
isn't useful in the same way that it was.
What I'd like to know: is there a method available for determining the distance between my object and the top of the user's screen (as opposed to between the object and the top of my content)? I'm using the latest version of Chrome.
Cheers
Upvotes: 4
Views: 1932
Reputation: 96240
is there a method available for determining the distance between my object and the top of the user's screen
Yes, there is – getBoundingClientRect:
“The returned value is a TextRectangle object, which contains read-only
left
,top
,right
andbottom
properties describing the border-box in pixels. top and left are relative to the top-left of the viewport.”
I made a (more than) crude example here, http://jsfiddle.net/7ceL8p3s/ – scroll the red box into view, and click on it – it will log the TextRectangle
object to console each time you click, and you’ll see the top
and left
values are relative to the viewport. (The viewport of the jsfiddle result frame that is – go to http://jsfiddle.net/7ceL8p3s/show/ to see it in a full window.)
And if you scroll it so that the box goes partly out of view on the top viewport border, so that only a lower part of it is visible, you will get negative top
values as well. (Same should happen for left
if you have a layout where the element might be scrolled out of view to the left.)
Upvotes: 2