1
votes

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');
  }
}
1
Probably because it isn't supported, stackoverflow.com/questions/20514596/… basically, make sure document.documentElement.scrollTop is giving you what you think it is giving you - Huangism
Ah, of course, thanks alot. - vrt1515

1 Answers

1
votes

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;