In order to monitor the hash state and determine if the browser's back or forward button were hence used, you must set up a polling loop. It will check the current hash against the last hash. If there is a change it will do something magical (whatever you want to do).
<script type="text/javascript"> /* set defaults */ var curHash = window.location.hash; /* check for a change in hash (back or forward buttons) */ setInterval(function() { if (curHash != window.location.hash) { curHash = window.location.hash; /* -- do what you need to do when the hash changes! -- */ } }, 250); </script>
The check time is set to 250 ms. But this can be tweaked for your particular needs.
There is rumors that in HTML 5 there will be a hash onchange event. This will really clean up the code, removing the need for polling. Until then, this is the next best thing.
Update 10/28/13 - Side Note: Checkout HTML5's push state for doing cool things like this w/o the hash. You can have the whole URL reflect a change in the DOM without the browser trying to go out and fetch a new web page. Pretty cool stuff. Some JavaScript frameworks like Backbone support both the hash change and the newer push state methods.
2 comments:
Thanks!
Thanks
Post a Comment