How do I navigate to hashtag after page load?

brunam picture brunam · Jan 15, 2013 · Viewed 28.7k times · Source

I want to do the inverse of what I've been finding so far. I'm setting a lot of heights with js and I want to navigate to the hashtag in the url after the page has loaded. I'm guessing this is simple but I'm not seeing the obvious answer... for an example, check here...

http://alavita.rizenclients.com/#story

Attempted this using the code...

$(window).load(function() {
    var hashTag = window.location.hash;
    window.location = '/' + hashTag;
}); 

doesn't actually take me to the top of the tagged section...

Answer

Onur Yıldırım picture Onur Yıldırım · Jan 16, 2013

If you simply want to change the hash after page loads:

window.onload = function (event) {
    window.location.hash = "#my-new-hash";
};

If you want to navigate to the URL with new hash:

window.location.href = "http://website.com/#my-new-hash";

If you want to listen for changes in the hash of the URL; you can consider using the window.onhashchange DOM event.

window.onhashchange = function () {
    if (location.hash === "#expected-hash") {
        doSomething();
    }
};

But it is not supported by every major browser yet. It now has a wide browser support. You can also check for changes by polling the window.location.hash on small intervals, but this is not very efficient either.

For a cross-browser solution; I would suggest Ben Alman's jQuery hashchange plugin that combines these methods and a few others with a fallback mechanism.

EDIT: After your question update, I understand you want the page to scroll to a bookmark?:

You can use Element.scrollTop or jQuery's $.scrollTop() method.

$(document).ready(function (event) {
    var yOffset = $("#my-element").offset().top;
    $("body").scrollTop(yOffset);
});

See documentation here.