Showing header on scroll up and hiding on scroll down not working well with DOMContentLoaded

Viewed 47

I want to add a scroll event to the window object in order to show the header on scroll up and hide it on scroll down, but only after everything is loaded.

The problem I am having is that when I refresh the page, sometimes the class hide is added to the header, but it shouldn't be. How can I resolve the problem? Here is the code:

document.addEventListener('DOMContentLoaded', () => {
  window.onscroll = function (e) {
    if (this.oldScroll > this.scrollY) {
      header.classList.remove('hide');
    } else {
      header.classList.add('hide');
    }
    this.oldScroll = this.scrollY;
  };
});
1 Answers

That is happening because on load the condition is false. So the else part is called. You would wanna use a else if to avoid this. Like so:

document.addEventListener('DOMContentLoaded', () => {
  window.onscroll = function (e) {
    if (this.oldScroll > this.scrollY) {
      header.classList.remove('hide');
    } else if (this.oldScroll < this.scrollY) {
      header.classList.add('hide');
    }
    this.oldScroll = this.scrollY;
  };
});
Related