Search the blog

If you want to scroll to an anchor tag when the page loads you have a problem where the browser will first jump to the location hash (e.g. page.html#foo) and then it will scroll once the document is ready.

What you want to do ideally is stop the browser from jumping and wait for jQuery to perform the animation based off the hash.

Add this in script tags to the head of your document.

window.psuedoHash = window.location.hash; // Store the hash for later
history.replaceState(null, null, ' '); // Remove it from the address bar and don't store it in the history

This will store the hash in a variable and then remove it from the URL.

Now in your scripts file use the stored hash and animate there with jQuery once the document or window is ready.

$(window).on('load', function() {

    if (window.psuedoHash) {
        
        $('html, body').animate({

            scrollTop: $(window.psuedoHash).offset().top

        }, 1000);

    }

});

This approach also means the anchors work as expected if JavaScript is disabled. One limitation, however, is that the hashes are not stored in the history. If you push the history using the History API then it is retained in the browser history but does not work as expected when you hit the back button (the URL updates but it does not scroll). It is possible to fix this — again using the History API — but that is beyond the scope of what I was using it for.

Tim Bennett is a Leeds-based web designer from Yorkshire. He has a First Class Honours degree in Computing from Leeds Metropolitan University and currently runs his own one-man web design company, Texelate.