'jQuery: Make smooth scroll function work after loading page/navigating to the page

I've got the code below in our boilerplate that seems to work fine in the current setup. It scrolls to the section on the page when you click the navigation menu link or a link in a slick slider. What I found hard to solve is making it work when navigating from another page back to the homepage. It'll add the #discover hash to the url just fine, for example, but it won't register it for some reason. It's been a while since I properly used jQuery 😅.

I've already added the standard on document ready code around the function hoping it would be that, but no dice. Hope anyone can clue me in about what's happening here.

$(function(){ });
/*
Only enable this when you want smooth scrolling!

Usage:
  - Give the anchor you want to scroll to a certain position a href which starts with # and the class "scroll" (<a href="#container" class="scroll"></a>)
  - Give the container you want to scroll to a name (<section name="container"></section)
  - ???
  - profit
*/
const scrollOffset = 0 // the amount of pixels the animation should scroll "extra" (When you have a sticky navigation for example)
$(function () {
  $(
    '.menu__item a[href*="#"]:not([href="#"]), .slider-list__link[href*="#"]:not([href="#"])'
  ).click(function () {
    if (
      location.pathname.replace(/^\//, '') ==
        this.pathname.replace(/^\//, '') &&
      location.hostname == this.hostname
    ) {
      var target = $(this.hash)
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']')
      $('body').removeClass('no-scroll')
      $('.navbar').removeClass('navbar--is-open')
      if (target.length) {
        setTimeout(() => { // This is used to prevent the animation from the menu closing from interfering with the scrolling animation. It could mess up the offsets otherwise
          $('html, body').animate(
            {
              scrollTop: target.offset().top + scrollOffset, // Scroll to the target
            },
            400
          )

          return false
        }, 500)
      }
    }
  })
})


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source