1

I have set up a simple function to add a class to header when scrolling some amounts of pixels from the top of the document, it works everywhere but not in Edge. Any ideas why that is ?

No errors in the console, nothing, just doesn't work.

const headerScrollClass = () => {
  window.addEventListener('scroll', throttle(callback, 100));
}

function throttle(fn, wait) {
  let time = Date.now();
  return function () {
    if ((time + wait - Date.now()) < 0) {
      fn();
      time = Date.now();
    }
  }
}

const callback = () => {
  if (document.documentElement.scrollTop > 100) {
    document.querySelector('.header').classList.add('header--top');
  } else {
    document.querySelector('.header').classList.remove('header--top');
  }
}
vrt1515
  • 163
  • 1
  • 3
  • 11
  • 2
    Probably because it isn't supported, https://stackoverflow.com/questions/20514596/document-documentelement-scrolltop-return-value-differs-in-chrome/33462363 basically, make sure `document.documentElement.scrollTop` is giving you what you think it is giving you – Huangism Aug 08 '19 at 19:49
  • Ah, of course, thanks alot. – vrt1515 Aug 08 '19 at 19:57

1 Answers1

1

As Huangism said, document.documentElement.scrollTop seems not supported by Microsoft Edge. You could try the example in w3schools. You'll find that if you only use document.documentElement, it will not work in Edge. So I think you should use document.body.scrollTop in Edge.

Reference: https://www.w3schools.com/jsref/prop_element_scrolltop.asp

You could try the following code to make it compatible in different browsers:

var scrollTop = window.pageYOffset 
            || document.documentElement.scrollTop  
            || document.body.scrollTop  
            || 0;
Yu Zhou
  • 11,532
  • 1
  • 8
  • 22