14

usinf javascript is it possible to work out the distance, or how far in pixels a window has been scrolled down?

Regards Phil

Phil Jackson
  • 10,104
  • 22
  • 95
  • 129

4 Answers4

11

This will work to get the distance of an element from the top of the document: document.documentElement.scrollTop

You need to make sure that the element is scrollable.

From Mozilla MDN:

If the element can't be scrolled (e.g. it has no overflow or if the element is non-scrollable), scrollTop is set to 0

Alex
  • 127
  • 1
  • 3
5

There is a dual check:

var dsocleft=document.all? iebody.scrollLeft : pageXOffset
var dsoctop=document.all? iebody.scrollTop : pageYOffset

For IE and others

Pifon
  • 346
  • 3
  • 16
  • I have noticed that Firefox and Chrome on Mac -- the jquery "scrollTop()" method does not work -- it always returns '0'. Also Firefox on Ubuntu also returns 0 – hypervisor666 Jul 30 '13 at 20:23
3

Catch all browsers including IE

var scrollTop = window.pageYOffset || (document.documentElement || document.body.parentNode || document.body).scrollTop

From http://www.javascriptkit.com/javatutors/detect-user-scroll-amount.shtml

Will
  • 401
  • 1
  • 5
  • 16
-3

You can get the scroll offset of the document with document.body.scrollTop.

Tatu Ulmanen
  • 119,594
  • 33
  • 182
  • 182
  • 5
    This doesn't work for me - I just scrolled up and down the page and document.body.scrollTop was always 0... – Felix Eve Oct 26 '12 at 17:53