Monday, May 20, 2024
29
rated 0 times [  32] [ 3]  / answers: 1 / hits: 64595  / 15 Years ago, fri, january 29, 2010, 12:00:00

How can I write the Javascript callback code that will be executed on any changes in the URL fragment identifier (anchor)?


For example from http://example.com#a to http://example.com#b


More From » event-handling

 Answers
11

Google Custom Search Engines use a timer to check the hash against a previous value, whilst the child iframe on a seperate domain updates the parent's location hash to contain the size of the iframe document's body. When the timer catches the change, the parent can resize the iframe to match that of the body so that scrollbars aren't displayed.



Something like the following achieves the same:



var storedHash = window.location.hash;
window.setInterval(function () {
if (window.location.hash != storedHash) {
storedHash = window.location.hash;
hashChanged(storedHash);
}
}, 100); // Google uses 100ms intervals I think, might be lower


Google Chrome 5, Safari 5, Opera 10.60, Firefox 3.6 and Internet Explorer 8 all support the hashchange event:



if (onhashchange in window) // does the browser support the hashchange event?
window.onhashchange = function () {
hashChanged(window.location.hash);
}


and putting it together:



if (onhashchange in window) { // event supported?
window.onhashchange = function () {
hashChanged(window.location.hash);
}
}
else { // event not supported:
var storedHash = window.location.hash;
window.setInterval(function () {
if (window.location.hash != storedHash) {
storedHash = window.location.hash;
hashChanged(storedHash);
}
}, 100);
}


jQuery also has a plugin that will check for the hashchange event and provide its own if necessary - http://benalman.com/projects/jquery-hashchange-plugin/.



EDIT: Updated browser support (again).


[#97717] Tuesday, January 26, 2010, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
herman

Total Points: 110
Total Questions: 90
Total Answers: 108

Location: Bosnia and Herzegovina
Member since Thu, Jun 24, 2021
3 Years ago
;