Div position relative to window?

Trying to find the position of a div relative to a window. I have a horizontal div and I want to get the left value relative to the window. So, if I scroll the second div to the left of the window, it will read “0”.

Not sure if this is possible without a parent div. Here is my fiddle: http://jsfiddle.net/FSrye/

edit: it should work as follows without a parent div.

http://jsfiddle.net/FSrye/1/

+4
source share
2 answers

Try to calculate it as a function of the position of the element relative to the scroll position of the window: http://jsfiddle.net/va836/

var position = $('selector').position().left - $(window).scrollLeft(); 

You may also need to consider the position relative to other elements if it is not a top-level element.

This is actually even simpler - just use offset() and omit the parent count.

 var position = $('selector').offset().left - $(window).scrollLeft(); 
+7
source

I think you can use scrollLeft() in a window to get the horizontal scroll size.

+1
source

All Articles