Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

133
Views
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)
      }
    }
  })
})
about 4 years ago ยท Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
ยฉ 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!