Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

body.scrollTop vs documentElement.scrollTop vs window.pageYOffset vs window.scrollY

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)?

like image 509
Himanshu P Avatar asked Oct 27 '13 13:10

Himanshu P


People also ask

What is Window scrollY?

scrollY. The read-only scrollY property of the Window interface returns the number of pixels that the document is currently scrolled vertically. This value is subpixel precise in modern browsers, meaning that it isn't necessarily a whole number.

What is Window pageYOffset?

The read-only Window property pageYOffset is an alias for scrollY ; as such, it returns the number of pixels the document is currently scrolled along the vertical axis (that is, up or down) with a value of 0.0, indicating that the top edge of the Document is currently aligned with the top edge of the window's content ...

Is scrollTop deprecated?

scrollTop is deprecated in strict mode.

Can I use document documentElement scrollTop?

Generally you can use (document. documentElement. scrollTop || document. body.


2 Answers

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) 
like image 147
Prinzhorn Avatar answered Oct 05 '22 21:10

Prinzhorn


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.

like image 28
jasonklein Avatar answered Oct 05 '22 20:10

jasonklein