I found this peace of code some where on the web.
I tried it and it works fine:
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);
})();
}
BUT when the function that would be called in the onHashChange many time, it will be repeated for ever.
onHashChange(function() {
console.log("changed");
});
when am at the same page and the hash is being changed, the console.log will be full of “changed” text even when I made only 3 changes for the hash in the page!
Well, am calling a function “instead of console.log” that at the same time will callback onHashChange again
Any trick to get over it?
Thanks 🙂
This should work well on hash change and url change via
history.replaceStateandhistory.pushState!