Use window.scrollY where possible, it's designed to be consistent across browsers. If you need to support IE, then I'd recommend the following to only use window.scrollY
if it's available:
typeof window.scrollY === "undefined" ? window.pageYOffset : window.scrollY
window.scrollY
will be evaluated as false if it returns 0, so doing window.scrollY || window.pageYOffset
would technically check window.pageYOffset
whenever window.scrollY
were 0, which obviously isn't ideal if window.pageYOffset
did not also equal 0.
Also note that if you need to get the scroll value frequently (every frame/every scroll) as is often the case, you might want to check if window.scrollY
is defined beforehand. I like to use this small helper function I wrote to do exactly that, along with using requestAnimationFrame
- it should work in IE10 and up.
function registerScrollHandler (callback) {
"use strict"
var useLegacyScroll = typeof window.scrollY === "undefined",
lastX = useLegacyScroll ? window.pageXOffset : window.scrollX,
lastY = useLegacyScroll ? window.pageYOffset : window.scrollY
function scrollHandler () {
// get the values using legacy scroll if we need to
var thisX = useLegacyScroll ? window.pageXOffset : window.scrollX,
thisY = useLegacyScroll ? window.pageYOffset : window.scrollY
// if either the X or Y scroll position changed
if (thisX !== lastX || thisY !== lastY) {
callback(thisX, thisY)
// save the new position
lastX = thisX
lastY = thisY
}
// check again on the next frame
window.requestAnimationFrame(scrollHandler)
}
scrollHandler()
}
Use the function like this:
registerScrollHandler(function (x, y) {
/* your code here :) */
console.log("Scrolled the page", x, y)
})