4

Trying to find the position of a div, relative to the window. I've got 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 function like this without a parent div.

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

wesbos
  • 25,839
  • 30
  • 106
  • 143

2 Answers2

9

Try calculating 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 might also have to factor in the position relative to other elements if it's not a top level element.

Actually, it's even easier -- just use offset() and omit the calculation of the parents.

var position = $('selector').offset().left - $(window).scrollLeft();
tvanfosson
  • 524,688
  • 99
  • 697
  • 795
  • For your example you might use `post.position().left + $('#wrapper').position().left - $(window).scrollLeft()` -- or the distance of the element from the edge of the window minus the current distance the window is scrolled left. – tvanfosson May 10 '11 at 00:27
  • @Wes - it's even easier using `offset()`. – tvanfosson May 10 '11 at 00:31
1

I think you can use scrollLeft() on the window to get the horizontal scroll amount.

Paul Sham
  • 3,185
  • 2
  • 24
  • 31