Search code examples
javascripthtmlcsssmooth-scrollingjs-scrollintoview

scrollIntoView - behavior is not working(JavaScript)


I know there are other questions on stackOverflow with the same question(2016 and older), but I went through them all and they do not solve my problem.

scroll into view works, when I click the button then the page goes to the specfic section it is suppose to go to but the behavior propery does not function.

const alllinks = document.querySelectorAll("scroll:link");

alllinks.forEach(function (link) {
  link.addEventListener("click", function (e) {
    e.preventDefault();
    const href = link.getAttribute("href");
    // Scroll to top
    if (href === "#") {
      window.scrollTo({
        top: 0,
        behavior: "smooth",
      });
    }
    //Scroll to other links
    else if (href !== "#" && href.startsWith("#")) {
      document.getElementById(href).scrollIntoView({
        behavior: `smooth`,
      });
    }
  });
});

Here's how the html looks at all the sections. (This is only one section as a example)

<a class="scroll nav-list--item btn" href="#how">How it works</a>
<section class="section-more container" id='how'>...</section>

This is all the code needed.

CODE PEN EXAMPLE


Solution

  • getElementById's argument must be the element id value and do not contain "#".

     document.getElementById(href).scrollIntoView({
        behavior: `smooth`,
      });
    

    This block of code throws TypeError because document.getElementById(href) with href = "#how" will return undefined, so when you was clicked in the link, the scroll behavior is just default behavior of the a link. May be you can want to correct it like:

    document.getElementById(href.slice(1)).scrollIntoView({
        behavior: `smooth`,
      });