Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

152
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!