Rabie_Rabit
Rabie_Rabit

Reputation: 31

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

Upvotes: 0

Views: 8290

Answers (2)

Vijay Kumawat
Vijay Kumawat

Reputation: 963

Add these additional properties too to make it work

element.scrollIntoView({
  behavior: 'smooth',
  block: 'start',
  inline: 'nearest'
});

EDIT: in you case, you just need to put the below css in your main style file, because the scrolling is not happening by the javascript code you wrote, it is happening because of the href of tag. you can even remove the javascript code

* {
    scroll-behavior: smooth
 }

Upvotes: -1

LocV&#39;s Nest
LocV&#39;s Nest

Reputation: 118

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`,
  });

Upvotes: 0

Related Questions