2
\$\begingroup\$

I did a little function which is listening to hashchanges.

What do you think about?

var onhashchange = function(code) {
    var checkHash = function(oldHash, code) {
        var hash = window.location.hash;
        var hashObject = hash.replace('#/','').split('/');

        if (hash !== oldHash)
            code(hashObject);

        setTimeout(function(){checkHash(hash, code);},100);
    }

    var oldHash = window.location.hash;

    setTimeout(function(){checkHash(oldHash, code);},100);
}

onhashchange(function(evt) {
    console.log(evt[0]); // Pagename after #/ - subcategories evt[1]... after slashes /
});
\$\endgroup\$

2 Answers 2

2
\$\begingroup\$

You could re-write everything into just this:

window.onhashchange = function locationHashChanged() {
    doWhatYouWantNowThatTheHashHasChanged();
    //or return something
}

And according to MDN, the browser support is not too bad (IE8+). But if you do need to support IE7 and friends, you can use the jQuery plugin.

Also, depending on what you're going to use that for, you'll probably want to read this article about browser state handling.

\$\endgroup\$
2
\$\begingroup\$

First of and maybe a bit off-topic. The is this feature in all modern browsers now: https://developer.mozilla.org/en-US/docs/Web/API/window.onhashchange and the support is good: http://caniuse.com/hashchange

Then the function. Perosnally I would use an anonymous function without storing it in a var first. I would pass in the hs 'unparsed' and simply pass the hash to the function instead of an array. It is snipplet that checks or the hash changes and should thus not be concerned on what the symbols in the hash mean.

Also, instead of using the setTimeOut and calling it allover your code. Simply use the setInterval function.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.