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

283
Visualizações
How to use element.scrollIntoView and scroll listener together?

Is it possible to use element.scrollIntoView and a "scroll" event listener together?

What i want to do with my code is check if the user scrolled by a certain element, if so, then the page should automatically scroll smoothly to the next section, to do this i tried to use a scroll listener and element.scrollIntoView with behavior smooth, and doing that causes a loop that makes the scroll go really slooow.

I also tried to remove the listener once the function executes, but that doenst work because i need to constantly execute that same function to check the scroll position, testing with console.log made me see that removing the listener makes it execute only once.

Here is the function:

let scrollBox = document.getElementById("scrollbox")
function onScroll(event){
    window.removeEventListener("scroll", onScroll);

    elementTop = scrollBox.getBoundingClientRect().top;
    if(elementTop < 800 && elementTop > 600)
    {
        divStop.scrollIntoView({block: "end", behavior: "smooth"});
    }
    
    event.preventDefault();
};


window.addEventListener("scroll", onScroll)

So, how should i proceed? is there a way to use then both together that i am missing, if not then how can i complete my objective/idea ? Please help.

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

0

You could use an IntersectionObserver. Whenever the element you observe is reached, you can then call the scrollIntoView method on the element you want to go to. You can then stop watching the first element if you want to prevent it to loop over and over.

const scrollBox = document.getElementById("scrollbox");

const divStop = document.getElementById("stop");

const scroller = new IntersectionObserver((entries) => {
  entries.forEach((entry) => {
    if (entry.isIntersecting) {

      divStop.scrollIntoView({ block: "end", behavior: "smooth" });
      scroller.unobserve(scrollBox);

    }
  });
});

scroller.observe(scrollBox);
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