Search code examples
javascriptsmooth-scrollingpolyfills

Smooth scroll polyfill not working inside a forEach loop


I'm using the smooth scroll polyfill npm package https://github.com/iamdustan/smoothscroll on a website I'm developing and despite trying for hours, I can't get it working. After importing and invoking the package I'm calling a function that adds an event listener to all links with a data attribute of "navigate-to" so that the appropriate element would be scrolled into view. Does anyone have any ideas what could be causing the problem? I suspect it might have something to do with the addeventlistener being appliead inside a forEach? Thanks in advance!

    import smoothscroll from "smoothscroll-polyfill";
    smoothscroll.polyfill();

    function anchorScrollTo() {
     document.querySelectorAll("[data-navigateTo]").forEach(function (e) {
     e.addEventListener("click", function (event) {
      document.querySelector(e.dataset.navigateto).scrollIntoView({ behaviour: "smooth" });
    });
  });
}
     anchorScrollTo()

Solution

  • After trying a few more solutions I noticed that the polyfill for some reason does not work with querySelectorAll, so I just created an array of classes that I loop over and select each of the elements with querySelector instead.