15

I would like to retrieve the current scroll position in Javascript, after some research I found this: window.scrollY and window.scollTop.

But the problem is that it does not work 100% on all browsers, is there something more reliable?

rudolph1024
  • 962
  • 1
  • 12
  • 32
user5171262
  • 153
  • 1
  • 1
  • 6
  • 1
    possible duplicate of [retrieve Scrollbar position with javascript](http://stackoverflow.com/questions/2481350/retrieve-scrollbar-position-with-javascript) – Zakaria Acharki Jul 29 '15 at 22:39

2 Answers2

31

The solution for JavaScript is:

var scrollPos = window.scrollY || window.scrollTop || document.getElementsByTagName("html")[0].scrollTop;

Or if you use jQuery (this is more reliable, due cross-browser support):

var scrollPos = $(window).scrollTop();
Orlandster
  • 4,706
  • 2
  • 30
  • 45
BigMac
  • 342
  • 3
  • 3
11

For cross-browser compatibility, use window.pageYOffset

https://developer.mozilla.org/en-US/docs/Web/API/Window/pageYOffset

callback
  • 3,981
  • 1
  • 31
  • 55