Here is another very useful piece of JavaScript, that you will not be able live without, when you create your first JavaScript App.
var onHashChange = function(event) {
//get hash function
var getHashValue = function() {
var arr = window.location.hash.split("#");
var hasValue = arr[1];
//sets default
if (typeof hasValue == "undefined") {
return false;
}
var hashLen = hasValue.indexOf("?");
if(hashLen>0){
hasValue = hasValue.substring(0,hashLen);
}
return hasValue;
}
//last hash
var lastHash = getHashValue();
//checker
(function watchHash() {
var hash = getHashValue();
if (hash !== lastHash) {
event();
lastHash = hash;
}
var t = setTimeout(watchHash, 100);
})();
}
onHashChange(function() {
//your on-change code here
});
So what is this good for? Well let's say you have an AJAX app, that goes from view to view, but all these views are just JavaScript functions running and updating your DOM. You can change your hash with each view, so when the user hits the "back" button, the hash goes to the previous hash, and now since you have a listener, you can reload/re-render your previous view. Sounds familiar? Actually, facebook.com uses this trick.
onhashchange is actually supported in IE8 so this code could improved a little by using the native IE8 support.