views:

33

answers:

3

Hi,

I'm creating a page where I want users to click on a link, and when they click on it, the current content of the page is replaced with new content (without actually leaving the same physical html page).

I'm doing this using the following javascript:

function ShowForm() 
{
var ele = document.getElementById("Page1");
ele.style.display = "none";
var ele = document.getElementById("Page2"); 
ele.style.display = "block";
}

HTML:

<div id="Page1">
    Fill out the following <a href="javascript:Showform();">form</a>.
</div>
<div id="Page2" style="display:hidden;">
    Form
</div>

This works great except that since it's on the same page, the back button on the browser doesn't work. This is confusing to users since they don't know that the content is on the same html page.

Is there a way to allow enable to back button to work in this kind of setup, where hitting the back button will take them back to the Page1 content?

Thanks in advance!

+2  A: 

If you change the hash when you change your content, it won't break the browser's back and forward functionality:

function ShowForm() 
{
    var ele = document.getElementById("Page1");
    ele.style.display = "none";
    var ele = document.getElementById("Page2"); 
    ele.style.display = "block";

    window.location.hash = 'page2';
}

Of course you'll need to put some more effort into this to make it work properly, but that's the idea.

Aillyn
+2  A: 

You'll have to do more than just change the history stack by changing the hash, you need to make your application aware of the back/forward buttons being pressed as well. There's a couple ways to do this. window.onhashchange is fired in most browsers but doesn't have complete support so it can't be relied upon alone.

An easier approach would be to get a plugin that allows for history tracking through AJAX applications. You may not be doing AJAX but the principle is the same, you want to track the state of the page and allow the navigation buttons to follow that flow.

Try these plugins:
http://www.overset.com/2008/06/18/jquery-history-plugin/
http://github.com/tkyk/jquery-history-plugin

Robert
You're right, I'm not using AJAX in this application, however the github plugin looks fairly simple to use, I'll give it a try on monday when I'm back in the office.Thanks!
J J