Force Reload on a Hash or Anchor Change with JQuery

I had a JQuery function that detected if there was a hash/anchor tag appended to the loaded URL.  If there was, it would scroll to the anchor tag on the page.

This was the function:

$(document).ready(function() {
    var hash = window.location.hash;	
    if(hash) {		
        $('html,body').animate({scrollTop: $(hash).offset().top-200}, 300, 'swing');
    }
});

This was great — the problem was, however, that if for some reason the hash changed but the page remained the same, it wouldn’t scroll to the new anchor. This was expected because DOCUMENT.READY will only fire once.

The most common method of detecting a hash/anchor change is using this function:

$(window).on('hashchange',function(){ 
    window.location.reload(true); 
});

This will force a reload whenever a hash tag changes. Now, if the URL changes, the page will reload and it will fire my original function detecting a hash/anchor tag.

For this particular instance, this method worked. It doesn’t always, and this may not apply to your problem, but in this case it made sense. It’s also very well supported.

Good luck!

1 Comment

  • This worked great for me and fixed my problem – it works with the browser back button too.

Leave A Comment

Your email address will not be published. Required fields are marked *