18

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

b3.
  • 7,094
  • 2
  • 33
  • 48
Phil Jackson
  • 10,238
  • 23
  • 96
  • 130

5 Answers5

13

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
  • 147
  • 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
4

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

William
  • 498
  • 1
  • 6
  • 18
0

The window object's scrollY property will give you the distance scrolled vertically.

window.scrollY on mdn

-3

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

Tatu Ulmanen
  • 123,288
  • 34
  • 187
  • 185
  • 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