r4tchet r4tchet - 10 days ago 5
Javascript Question

My JavaScript doesn't work in Internet Explorer

I have a script on my site that works in every browser, except Internet Explorer. Can someone help me with why this doesn't work?



var header = document.getElementById('header');
var picturebg = document.getElementsByClassName('picturebg')[0];
var arrow = document.getElementsByClassName('toTop-transparent')[0];
var supportPageOffset = window.pageXOffset !== undefined;

window.onscroll = function() {
"use strict";
var y = window.scrollY;

if (y > 7) {
header.className = 'header-colored';
arrow.className = 'toTop';
picturebg.className = 'picturebgns';
} else {
header.className = 'header-transparent';
arrow.className = 'toTop-transparent';
picturebg.className = 'picturebg';
}
};





The console doesn't give any errors, it just doesn't work. I have another jQuery script that runs just fine.

I've seen the other question here about the same thing, but it didn't help in any way.

Appreciate all help!

Answer

Certain properties used in your snippet are not supported by IE.

From the MDN page on scrollY:

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.

It appears you already have found the check for pageOffset support, so also check if non-standard properties are supported (e.g. CSS1 is compatible):

var isCSS1Compat = ((document.compatMode || "") === "CSS1Compat");

var y = supportPageOffset ? window.pageYOffset : isCSS1Compat ? document.documentElement.scrollTop : document.body.scrollTop;

Try this sample, using addEventListener() instead of onscroll.

var header = document.getElementById('header');
var picturebg = document.getElementsByClassName('picturebg')[0];
var arrow = document.getElementsByClassName('toTop-transparent')[0];
var supportPageOffset = window.pageXOffset !== undefined;
var isCSS1Compat = ((document.compatMode || "") === "CSS1Compat");



header.addEventListener('scroll', function(event) {
  "use strict";
  var y = supportPageOffset ? window.pageYOffset : isCSS1Compat ? document.documentElement.scrollTop : document.body.scrollTop;
console.log('y: ',y);
  if (y > 7) {
    header.className = 'header-colored';
    arrow.className = 'toTop';
    picturebg.className = 'picturebgns';
  } else {
    header.className = 'header-transparent';
    arrow.className = 'toTop-transparent';
    picturebg.className = 'picturebg';
  }
});
<div id="header" style="height: 50px; overflow: scroll;">
  <img  class="picturebg" src="https://www.gravatar.com/avatar/684fa9ff80577cbde88ffbdebafac5b4?s=32&d=identicon&r=PG&f=1" />
  <div id="arrow" class="toTop-transparent">&darr;</div>
  </div>