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

204
Visualizações
Three cases on scroll - function inside an if

I need to set three different background on a navbar:

1. No background if the page is less than 400 px of scrolling

2. Two different colors if the scroll of the page is more than 400 px: a) blue when I scroll down b) green when I scroll up.

I've tried to use the following code, but it seems like after I enter in the first IF, the function continue to work even if the page is less than 400px.

    window.onscroll = function() {scrollFunction()};

    function scrollFunction() {



    if (document.body.scrollTop > 400 || document.documentElement.scrollTop > 400) { 
    
    var prevScrollpos = window.pageYOffset;
    window.onscroll = function() {
    var currentScrollPos = window.pageYOffset; 
    if (prevScrollpos > currentScrollPos) {
    document.getElementById("nav1").style.background = "rgba(0, 41, 51,1)";
    } else {
    lastScroll = currentScroll;
    document.getElementById("nav1").style.background = "rgba(68,78,36,1)";
    }
    prevScrollpos = currentScrollPos;
    } else {
document.getElementById("nav1").style.background = "rgba(0,0,0,0)";
}
}

Thanks!

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can use this script:

<script>
  window.onscroll = function () { myFunction() };

  function myFunction() {
    if (document.body.scrollTop > 400 || document.documentElement.scrollTop > 400) {
      var lastScrollTop = 0;

      window.addEventListener("scroll", function () {
        var st = window.pageYOffset || document.documentElement.scrollTop;
        if (st > lastScrollTop) {
          document.getElementById("nav").style.background = "rgba(0, 41, 51,1)";
        } else {
          document.getElementById("nav").style.background = "rgba(68,78,36,1)";
        }
        lastScrollTop = st <= 0 ? 0 : st;
      }, false);
    } else {
      document.getElementById("nav").style.background = "rgba(0,0,0,0)";
    }
  }
</script>
about 4 years ago · Juan Pablo Isaza Relatório

0

Do not attempt to assign two functions to window.onscroll, which is a property and can hold only one function.

Here is what is going on with your current code:

  1. An annonymous function is declared (it calls scrollFunction) and assigned to window.onscroll
  2. At the very first scroll, scrollFunction is called. If the page has not scrolled yet beyond 400px, the if block is not executed.
  3. As soon as the page goes beyond 400px, prevScrollpos is declared... Then the function previously assigned to window.onscroll is overwriten with a new one.

That is why the comparison for 400px isn't done after that. It is out of that second function. The first one got lost in the nothingness.

Here is what you want to achieve:

// This variable needs to be global
let prevScrollpos = 0;

// This getElement can also be global
let nav1 = document.getElementById("nav1")

function scrollFunction() {

  // This varable needs to be local
  let currentScrollPos = window.pageYOffset;

  if (document.body.scrollTop > 400 || document.documentElement.scrollTop > 400) {

    // Determine scroll direction
    if (prevScrollpos > currentScrollPos) {
      nav1.style.background = "rgba(0, 41, 51,1)";
    } else {
      nav1.style.background = "rgba(68,78,36,1)";
    }
  }
  
  // If below 400px
  else {
    nav1.style.background = "rgba(0,0,0,0)";
  }
  
  // Update this variable for the next iteration
  prevScrollpos = currentScrollPos;
  
  // For this demo only
  console.clear()
  console.log(currentScrollPos)
}

// Assign the scrollFunction reference to the window property
window.onscroll = scrollFunction;
body {
  height: 1000px;
}

#nav1{
  position: sticky;
  top: 4px;
  height: 100px;
  border: 1px solid black;
}
<div id="nav1"></div>

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