I've got the following script on my site, intended to change the body class when the user scrolls more than 20px away from the top of the viewport.
(function ($) {
/// Make nav opaque on scroll
window.addEventListener('scroll', function () {
document.body.classList[
window.scrollY > 20 ? 'add': 'remove'
]('scrolled');
});
})(jQuery);
It works perfectly on Chrome, Safari and Firefox, but not on IE11.
What am I missing?
According to MDN, IE11 does not support window.scrollY. Instead you could use window.pageYOffset
, which is an alias for window.scrollY
.
As mentioned on MDN,
The pageYOffset property is an alias for the scrollY property:
window.pageYOffset == window.scrollY; // always true
For cross-browser compatibility, use window.pageYOffset instead of window.scrollY. Additionally, older versions of Internet Explorer (< 9) do not support either property and must be worked around by checking other non-standard properties. A fully compatible example:
var supportPageOffset = window.pageXOffset !== undefined; var isCSS1Compat = ((document.compatMode || "") === "CSS1Compat"); var x = supportPageOffset ? window.pageXOffset : isCSS1Compat ? document.documentElement.scrollLeft : document.body.scrollLeft; var y = supportPageOffset ? window.pageYOffset : isCSS1Compat ? document.documentElement.scrollTop : document.body.scrollTop;
In your case if you intend to support IE 11, you can directly replace scrollY
with pageYOffset
:
document.body.classList[
window.pageYOffset > 20 ? 'add': 'remove'
]('scrolled');
});
Here's a working fiddle: https://jsfiddle.net/wg3nj06h/2/