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

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;
  };
});


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source