Let’s say you want to build photo gallery. Something like this:
You want to open next and previous photos without page reload, using Ajax. One problem with this is that browser’s back button stops working. Fortunately, it’s easy to fix with jQuery Address plugin from Asual. I tried using this plugin and it worked very well. I’ve put together a simple demo.
For simplicity, let’s display just a number instead of actual photo:
Every time you click right arrow the number increases; left arrow decrements the number by one. Simple! Back and forward buttons should work. Also, it would be nice to have different titles in the history:
The code:
$(function ()
{
$.address.strict(false);
$.address.externalChange(function(e)
{
switchTo(e.value);
});
$("#lnk_prev").click(function(e)
{
e.preventDefault();
var i = $("#number").text() * 1 - 1;
switchTo(i);
$.address.value(i);
});
$("#lnk_next").click(function(e)
{
e.preventDefault();
var i = $("#number").text() * 1 + 1;
switchTo(i);
$.address.value(i);
});
});
function switchTo(i)
{
$("#number").text(i);
$.address.title(i);
}
The magic happens in click handler. $.address.value method changes page address and adds browser history point. You need to cancel navigation by calling e.preventDefault() — otherwise browser would follow the link and two history entries would get created.
Note that you need to disable plugin’s strict option, otherwise it would add slash symbol immediately after hash symbol, like this: #/11.