0

I am using jQuery + jQuery UI and currently have the following code:-

$(function() {
  $('a[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) +']');
      if (target.length) {
        $('html, body').animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }
  });
});

I get the scrolling effect when the scroll to is on the same page, but if I load a new page it doesn't scroll to that section, e.g. from /home/ to /about/#section3

How can I get this to work for both on same page anchors and scroll to anchor when loading a new page?

nsilva
  • 5,184
  • 16
  • 66
  • 108
  • Have you tried initiating the smooth scroll by using `$(window).load()`? – ntgCleaner May 13 '16 at 19:51
  • why the downvote? really dont understand sometimes – nsilva May 13 '16 at 19:58
  • There isn't a good way to have it scroll on the new page. You would have to wait until the page is done loading so that you can accurately target where you want it to scroll, and by then the browser's default jump to target will have already happened. – Kevin B May 13 '16 at 20:07
  • @nsilva, Not sure who down voted but it's unnecessary. I've evened it up. – ntgCleaner May 13 '16 at 20:09

1 Answers1

1

I can't post a comment (due the reputation).

Did you try this solution : Smooth scroll to anchor after loading new page

I used it on a project and it worked fine. Just look at the comments of the answer ;)

Community
  • 1
  • 1
Pierrou
  • 303
  • 3
  • 21
  • Yep this works, just had to change the links from `/about/#section` to `/about#section` (remove the extra forward slash) – nsilva May 13 '16 at 20:28