10 August 2009

jQuery browser history manager

Despite being the creator of JSquared, I have recently had cause to use jQuery.

For the project where it is in use, I needed a browser history manager and after a very rapid cursory search, none came up that caught my eye. So, I decided to port my browser history manager from JSquared to jQuery and I woule like to make it available for you to use as well.

It works like all other browser history managers, appending named items with a value onto the hash portion of the URL in a QueryString like format.

The port is based on the new browser history manager that will be part of the next version of JSquared and it extends the jQuery object. You can download it here.

Using it could not be simpler. You set up named items you wish to listen for changes on and provide a callback function for when the change occurs. You can also update the value of an item as well.

To listen for changes, simply do the following:

$.url.listen( "myItemName", function(e, itemValue, itemName) {
    //perform some actions

Your callback function will be called when the user goes back and forwards and the value of your named item changes. The callback function will also get called if the user comes to your site from a bookmark and your item has a value.

To update the value of an item and create an entry in the users history, just do the following:

$.url.update( "myItemName", "myNewValue", false);

The third parameter to the update method is called "dontUpdateUrl". When set to true, the value shown to the user in the URL will not change, but the value internally within the browser history manager will. This is useful is you are updating many items and only wish to create one history point.

The new value can be any string and the object does not check that the length of the URL is safe - most browsers restrict URL's to around 2000 characters.

Please do feedback on whether this is working well for you.


irishsteve said...

This looks really useful, but do you have a working example anywhere? Couldn't find one on the demos site. Cheers!

Anonymous said...

Was not able to get working...

// Set item to watch...
$.url.update( "tmpMenuItem", "#somedDivId", false );

// Event Listener...
$.url.listen( "tmpMenuItem",
function(e, itemValue, itemName) {
//perform some actions
alert( itemValue );