I'm having a little difficulty working out how to use the jQuery address plugin - http://www.asual.com/jquery/address/- with my limited jQuery/javascript knowledge and would seriously dig some help!
So far my code looks like this:
jQuery(function($) {
$.ajaxSetup({ cache: false });
var hijax = $('ul.hijax a');
var loader = $('<div id="spinner"></div>');
var container = $('#ajax-container');
hijax.address(function() {
dis = $(this);
hijax.removeClass('ajax-on');
dis.addClass('ajax-on');
var url = dis.attr('href') + ' #biog-container';
container.html(loader).load(url);
return dis.attr('id');
});
});
Which I'm hoping is fairly self-explanitory. I have an ul
of links to pages where I load via AJAX the contents of a div
with an id
of biog-container
. The AJAX works ok and the url is updated with the id
s of the links, but when I click on the back button, the url changes, but the content remains the same.
Any thoughts, am I being stupid?!
To be honest, the address
method doesn't do too much in the way of work for you. Actually, the plugin doesn't add support automatically.
However, it's pretty simple to do. You just have to setup the handler for the change
method:
$.address.change(function(e){
// The function receives a single eventobject parameter that contains the
// following properties:
// value, path, pathNames, parameterNames,
// parameters, queryString
/* Do something based on e */
});
When the address is changed, your function gets fired. There are also other events internalChange
and externalChange
that you can set up to fire when the address change occurs internally or externally.
Edit: Just to expand on the above:
This is a full blown example of it working. In other words, you don't need to call anything else in the plugin for it to work:
// Override the click events of links
$("a").click(function(e) {
e.preventDefault();
$.address.path(this.id);
});
// Method called with the address changes
$.address.change(function(e) {
// This is called when the
$("#content").html("Something based on " + e.value);
});
When the links are clicked, it sets the address path (in terms of the plugin) to the ID of the link. This generates an action so that the back/forward works correctly. It doesn't change the link itself so if JavaScript isn't enabled it will go to whatever the link address was.
The $.address.change
bit sets the handler. This is where you would load the content. In my example, it uses e.value
to get the value of the address path. So that would be something like /link1
, /link2
, etc. This handler gets called when the link is changed internally (by the plugin) or externally (by the browser back/forward).
Note: I noticed that this doesn't work flawlessly with jQuery 1.5.1. I'm pretty sure it has something to do with the change to jQuery 1.5 attribute selectors (which the address plugin seems to use). jQuery 1.4 works fine though.