Vesica Blog Taking museums and art collections to the cloud

January 21, 2013

Tech Talk: URL Hashing and JQuery UI Tabs

Whilst Vesica uses JQuery, what’s discussed in this article is not used in Vesica, but in a similar application we helped build at the  NHS (National Health Service) which borrows from the Vesica interface.

The application in question is a single page application, so virtually everything is done via AJAX. The URL receives different parameters via a URL hash, which updates different sections of the page DOM or accesses different parts of the interface, including JQuery UI tabs. These single page, multiple hash URLs can be called via a bookmark URL, or will trigger on a url change in the browser. What’s important to note here is that in an application like this, when you submit data, all you really need to do is change the URL – your hashing managing JavaScript should do the rest for you (in terms of routing your data to the server side, not actual processing). I’ll also show you some JavaScript to deal with JQuery UI tabs after your page loads as working with hashing will disable the default URL behaviour that allows you to call tabs via the URL.

Requirements

If it’s not self-explanatory, you need the following to accomplish this:

  • JQuery - http://jquery.com/download/
  • JQuery UI - http://jqueryui.com/
  • JQuery Hashchange plugin from Ben Alman - http://github.com/cowboy/jquery-hashchange/raw/v1.3/jquery.ba-hashchange.js and http://benalman.com/projects/jquery-hashchange-plugin/
Please load the JavaScript libraries in your page (preferably in the header) in the order listed.

How it works

Here is what we need to cover:

  1. Someone either loads a URL in their browser which is part of your single page application (this could be via a bookmarked URL or by simply typing or pasting in the address bar), in which case you simply need to pick up the URL, process, and update the page.
  2. Someone performs an action that will change the URL of your application – which should either update a database or update the page, or whatever it is supposed to do in your application.
The JQuery Haschange plugin will only help you accomplish number 2. Number 1 is simple JavaScript / JQuery.
So how does your application know that the URL in the browser has changed after the #? With the following code.

So if your existing URL looked like http://example.com/#Page1 and you changed it to http://example.com/#Page2 with an or a