Thursday, May 13, 2010

Hash Changing, detecting the Back button in JavaScript

If you use gmail and you are a web developer, you have probably noticed that they use hash or anchor links (e.g., "example.html#hash") to make your browser's back button very effective. These hash or anchor links were designed to bring your browser to a certain position in a page. Often they are used on help pages or FAQ pages to make the browser window scroll to a certain point. But, interestingly, they can also be used to set certain JavaScript states, when configured properly.

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);

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.


Anonymous said...


Anonymous said...