r4tchet r4tchet - 9 days ago 5
Javascript Question

Why wont this script work in Firefox?

I'm having this script, and it works fine in every browser except firefox.



var header = document.getElementById('header');
var arrow = document.getElementsByClassName('toTop-transparent')[0];
window.onscroll = function () {
"use strict";
if (document.body.scrollTop > 7) {
header.className = 'header-colored';
arrow.className = 'toTop';
} else {
header.className = 'header-transparent';
arrow.className = 'toTop-transparent';
}
};





The script doesn't seem to load at all. It's supposed to change the color of my header on scroll, and bring forth a 'back to top' button, but in firefox it does nothing. Any ideas on why this doesn't work?

I've tried updating browser to latest version, start in safe-mode without any add-ons.

Edit: I no longer have any errors in console on my site. The script still won't load, it seems like there is something in the script that firefox doesn't understand?

Answer

This code works in IE, Chrome and FF:

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

window.onscroll = function() {
  "use strict";
  var y = supportPageOffset ? window.pageYOffset : isCSS1Compat ? document.documentElement.scrollTop : document.body.scrollTop;

  if (y > 7) {
    console.log('here 1')
    header.className = 'header-colored';
    arrow.className = 'toTop';
  } else {
    console.log('here 2')
    header.className = 'header-transparent';
    arrow.className = 'toTop-transparent';
  }
};

Fiddle: https://jsfiddle.net/zevane/zf8d4u36/

Documentation: https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollY

Comments