Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

119
Visualizações
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;
  };
});
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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;
  };
});
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda