Smooth scroll to anchor after loading new page Smooth scroll to anchor after loading new page jquery jquery

Smooth scroll to anchor after loading new page


As browsers automatically detect the hash and take you to that position...
It occurs to me that you could first reset the scroll position to 0 and then made the smooth scrolling.

Something like...

// to top right awayif ( window.location.hash ) scroll(0,0);// void some browsers issuesetTimeout( function() { scroll(0,0); }, 1);$(function() {    // your current click function    $('.scroll').on('click', function(e) {        e.preventDefault();        $('html, body').animate({            scrollTop: $($(this).attr('href')).offset().top + 'px'        }, 1000, 'swing');    });    // *only* if we have anchor on the url    if(window.location.hash) {        // smooth scroll to the anchor id        $('html, body').animate({            scrollTop: $(window.location.hash).offset().top + 'px'        }, 1000, 'swing');    }});

Edit: Move the scroll(0,0)outside $(function(){...}); to prevent flickering.
Also, Snippet with working example was added.
The effect is best appreciated when viewed in full screen