alt
alt

Reputation: 13947

Make the browser reload when user adds hash to to URL

So let's say you have a URL like this: http://yoursite.com/#stackoverflow

If I type a new hash into the address bar, it tries to find that ID on the page. Is there amy way (possibly with javascript?) to detect that browser activity and then force the page to reload at that URL?

Thanks!

Upvotes: 0

Views: 148

Answers (3)

Jashwant
Jashwant

Reputation: 29025

Worth a look,

This little plugin provides an abstraction for cross browser support.

http://benalman.com/projects/jquery-hashchange-plugin/

Upvotes: 0

James
James

Reputation: 112000

You need to bind to the hashchange event:

window.onhashchange = function() {
    window.location.reload();
};

Careful though: some older browsers do not support this event (see this), so you'll need a polyfill for those.

Here's an example plus a polling technique for older browsers:

if ('onhashchange' in window) {
    window.onhashchange = function() {
        window.location.reload();
    };
} else {
    var hash = window.location.hash;
    setInterval(function() {
       if (window.location.hash !== hash) {
           window.location.reload();
       }
    }, 100);
} 

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1075925

On newer browsers, you can use the hashchange event. Support for it is pretty good, actually. On older browsers, you have to poll the location.hash (e.g., with setInterval or setTimeout).

Upvotes: 0

Related Questions