Friday, August 22nd, 2008p>IE 8 has an onhashchange event, and Ajax history / bookmark management has been a long time problem of choice for developers.
Zach Leatherman has revisited the problem and has another solution that doesn’t require setInterval to check on the location.
- On initialization, we load an iframe onto the page that is positioned absolutely at -500px,-500px so the user can’t see it. It is a skeleton page that only needs cross browser code to add an “
onscroll” event, and to be able to calculate the scrolled position of the iframe itself. For my example, I use jQuery and the dimensions plugin to accomplish this, but it could easily be trimmed down to only the bare essentials (or ported to a different library).
- To add an AJAX history entry into the browser’s history under an assigned hash string, we first add a
<a name="hashString">hashString</a>to the
<body>tag of the iframe. Using css to increase the size of the a tag proportional to the iframe’s height, we can guarantee scrolling will happen.
- Then, we change the
location.hashof the iframe to point to that
<a>tag. This will scroll the iframe to the content, and create a new entry in the browser’s
- Inside the iframe, we have our
onscrollevent that fires when the scrolling in the previous step took place. (Minor IE-related workaround: The browser’s
historyobject is changed, but the hash property doesn’t when attempting to read it later. Instead, we find the
<a>that matches up with the scrollY/pageOffsetY property inside of the iframe, and retrieve the matching hash from the
The solution gives you history management and back button support in one fell swoop, with the side effect of not having bookmarkability (since the iframe is updated).