0

When I click href #demo-1 from home page to another page with ection id='demo-1'. How when loading the page with id='demo-1', that it will scroll down from the top of the page. If I use https://stackoverflow.com/a/3432718/6891215 it will jerk and not scroll from the top of the page down to that section.

Many thanks!

1 Answers1

0

The code below allows you to scroll on both same and external pages. To make the link work you need to give it a class .scroll. If you're linking to an anchor link on an external page, give the link a data-target="external" as well.

$(document).ready(function() {
    $('html, body').scrollTop(0);
    var str = window.location.href;
    if(str.indexOf('#') > -1) {
        var anchor = str.substring(str.indexOf('#'));
        setTimeout(function() {
            $('html, body').animate({scrollTop: $(anchor).offset().top}, 'slow');
        }, 100);
    }

    $('a.scroll').click(function(e) {
        var trg = $(this).attr('data-target');
        if(trg != 'external') {
            e.preventDefault();
            var href = $(this).attr('href');
            $('html, body').animate({scrollTop: $(href).offset().top}, 'slow');
        }
    });
});

The link to an anchor on an external page will look like this:

<a href="inner.html#demo_2" class="scroll" data-target="external">DEMO 2</a>

Also, you can link to an anchor on the same page. In this case, you won't need to add any data-target. I wrote the script the way that is supports both:

<a href="#demo_3" class="scroll">Go TO DEMO 3</a>
  • You're most welcome @dev-dreams. If the code is working for you please feel free to consider the answer as the solution by accepting it. Thank you. – Amin Shahrokhi Jan 10 '22 at 11:45