53

When trying to find out how much a web page has been scrolled from the top, which of these should one use:

document.body.scrollTop,

document.documentElement.scrollTop,

window.pageYOffset,

window.scrollY

Which one(s) would I choose in these 2 separate scenarios:

a) If I wanted maximum compatibility (across the main browsers used currently)?

b) If I wanted code that was most standards compliant/future-proof/strict-mode-compatible (but didn't care about supporting old/non-standard browsers)?

Elias Zamaria
  • 96,623
  • 33
  • 114
  • 148
Himanshu P
  • 9,586
  • 6
  • 37
  • 46

5 Answers5

38

I'm using three of them in the skrollr source

return window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;

https://github.com/Prinzhorn/skrollr/blob/b98d40820b9864be275e81af382045d72cc5a08a/src/skrollr.js#L627

a) So far it's working across all browsers (nobody complaint in the past year).

b) Since it will use the first one that is defined, I guess it's pretty future proof and stable.

If you're fancy you could do this as well

Math.max(window.pageYOffset, document.documentElement.scrollTop, document.body.scrollTop)
Prinzhorn
  • 22,120
  • 7
  • 61
  • 65
4

Given that skrollr does not use window.scrollY, this may have been obvious, but as further answer to the original question: window.pageYOffset is an alias for window.scrollY. See Window.scrollY.

jasonklein
  • 51
  • 3
3

To Prinzhorn's answear:

Since body and documentElement is undefined in Chrome/Firefox, better use:

return window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;

Tested myself.

Tom
  • 1,064
  • 1
  • 10
  • 7
  • 3
    document.body.scrollTop in FF doesn't work and document.documentElement.scrollTop behaves strange: values sometimes are odd. – willy wonka Feb 06 '17 at 05:43
3
console.log('body.scrollTop : ' + document.body.scrollTop);
console.log('documentElement.scrollTop : ' + document.documentElement.scrollTop);
console.log('window.pageYOffset : ' + window.pageYOffset);
console.log('window.scrollY : ' + window.scrollY);

Output 1:

0

184.8000030517578

184.8000030517578

184.8000030517578

Output 2:

0

185.8000037517577

185.8000037517577

185.8000037517577

And so on...

Tested on Google Chrome - Version 85.0.4183.121 (Official Build) (64-bit)

document.body.scrollTop

It always gives 0 here but others three works perfectly.

iamfnizami
  • 163
  • 1
  • 8
1

Chrome uses documentElement.scrollTop, firefox uses body.scrollTop

yaya
  • 7,675
  • 1
  • 39
  • 38
  • this does not seem true for me. i can confirm what @iamfnizami said. `document.body.scrollTop === 0` always, for chrome and firefox. – somedotnetguy Feb 09 '23 at 15:45