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

153
Visualizações
How to add a scroll function with JS?

I am trying to add a scroll function to my landing page so that when the navi bar link is clicked, it smoothly scrolls to the section. instead of CSS, I should use JS, 'addEventListener','preventDefault' and ''scrollIntoView() to achieve this. I've been trying and trying for days, it just dosen't work, please help me!

here is my my CodePen link:

https://codepen.io/Qinisfighting/pen/bGYKEGe

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

0

I rewrote the code that you commented, but also changed a major part when you created the menu links.

const clickItems =  document.querySelectorAll('.menu__link');

for (const clickItem of clickItems) {
      clickItem.addEventListener("click", function(e){
        e.preventDefault();
        document.querySelector(e.currentTarget.dataset.href).scrollIntoView({behavior: "smooth"});
    });
  }

The main difference is that I changed your href attribute in the menu links into a data-href attribute, otherwise the native behavior would scroll down to your sections, just like any link would do.

navList += `<li id="${sectionName}"> <a class="navbar__menu menu__link" data-href="#${section.id}">${sectionName}</a></li>`;
about 4 years ago · Juan Pablo Isaza Relatório

0

You can search for the element and move directly

document.getElementById("myElement").scrollIntoView();

"behavior" Defines the transition animation. One of auto or smooth. Defaults to auto.

Post: How do I scroll to an element using JavaScript?

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