Home > Mobile >  How to add a scroll function with JS?
How to add a scroll function with JS?

Time:03-15

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

CodePudding user response:

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  data-href="#${section.id}">${sectionName}</a></li>`;

CodePudding user response:

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?

  • Related