Deep Linking in jQuery

While working on a jQuery animated website, I needed to deep link my website. If you are not familiar with deep linking, it is a process mostly used in Flash to store the state of a Flash object. This is done through javascript using the # in the URL. SwfAddress does a great job.

Usual also makes a jQuery plugin called jQuery Address. Deep linking the jQuery animation has two major benefits:

  • A user can share the URL, and the recipient will go to the exact state the sender intended.
  • You can add analytics to the states, so you can track how users are interacting with your site.

Include jQuery and jQuery Address in your <head> tag:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript" language="javascript"></script>
<script src="scripts/jquery.address-1.2rc.min.js" type="text/javascript" language="javascript"></script>

Use the following javascript code to call to initiate the page state change:

window.location = "#page1";

Attach the update function to URL location changes:

$.address.change(function(event) {updatePage();});

The updatePage() function sets the new page title, and updates the menu.

function updatePage()
{
	var baseTitle = "My Page Title";
	if(window.location.hash != '')
	{
		if (window.location.hash == '#page1') {
			$.address.title("Page 1 - " + baseTitle);
			loadMenu1();
		}
		else if (window.location.hash == '#page2') {
			$.address.title("Page 2 - " + baseTitle);
			loadMenu2();
		}
	}
}

Inside the updatePage() function, you can add any other functionality, such as analytics.