Sunday, July 19, 2009

Saving last view using the URL anchor

I had a page with 3 links in it, each link changed the className of 3 divs so that 2 were hidden and 1 was visible... the issue was that when a user clicked a link the 'viewstate' was lost. Using a similar methodology as AJAX back button I cobbled together the following code to hide the divs and retreive the state when a user returned to the page using the back buttons.

// HTML Document
<a href="#div1" onclick="reveal('div1');">Button 1</a>
<a href="#div2" onclick="reveal('div2');">Button 2</a>
<a href="#div3" onclick="reveal('div3');">Button 3</a>

<div id="div1">Div 1</div>
<div id="div2">Div 2</div>
<div id="div3">Div 3</div>

<script type="text/javascript">

// JavaScript Document
function getObject(name){
var ns4 = (document.layers) ? true : false;
var w3c = (document.getElementById) ? true : false;
var ie4 = (document.all) ? true : false;
if (ns4) return eval('document.' + name);
if (w3c) return document.getElementById(name);
if (ie4) return eval('document.all.' + name);
return false;

function closeall(){
getObject('div1').className = 'closed';
getObject('div2').className = 'closed';
getObject('div3').className = 'closed';

function reveal(which){
document.location = '#'+which;
var query = location.href.split('#');
if((query[1].length) > 0){
what = query[1];
else {
what = which;
getObject(what).className = 'open';

No comments: