Using Asual jQuery Address plugin for photo gallery

Click here to view demo

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.

6 thoughts on “Using Asual jQuery Address plugin for photo gallery

  1. Thanks for this example. I’m not sure if I will use this plugin but this was certainly helpful.

  2. The jQuery Address seems vast at first sight, your tutorial is definitely helpful to use it, thanks!

  3. So what would the code look like if I were using this inside of a image gallery or slideshow?

  4. Very nice and simple tutorial. Took a little bit to figure it all out and apply it to my website but this was a huge help. Note that on the function that sends the old link into the switchTo function, e.value will pass the URL. I was mistakenly trying with just value and it wasn’t working. Cheers!

Leave a Reply

Your email address will not be published. Required fields are marked *