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.
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/
How it works
Here is what we need to cover:
- 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.
- 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 following line will monitor hash changes on the page this JS gets loaded into
// If the URL has changed, any code here gets executed. For instance, you could alert something:
alert('The URL has has changed.');
So if your existing URL looked like http://example.com/#Page1 and you changed it to http://example.com/#Page2 with an or a
This is the easy bit – now for how you would pick up different parts of your URL, splice them up and send them to your scripts as needed to process, and then perhaps load a JQuery UI tab on your page.
Let’s clarify what we have in our example.
We are trying to load a different type of product based on a type parameter, followed by an ID, followed by a bunch of parameters that style the image and options that get displayed for the product.
So, if you were using PHP and building your URL query string, it might look a bit like:
If you wanted to load a particular JQuery tab on this page that had the id ‘dimensions’, your URL would become:
When the page loaded, JQuery UI would know you want to load the dimensions tab and it would simply make it active.
But using the $(window).hashchange() function above will break this default JQuery UI functionality.
So, our goal, given our single page application, is to be able to reload a certain part of our page based on a URL that looks like the following:
The way to read the above your URL is: Give me the product page with bottle No. 3426 in the colour green and display the dimensions tab on the product page. You could change any of the values above to process different data – so you could have product, category or generic types of pages, hundreds of different products and hundreds of different colours.
Vesica, 16-24 Underwood Street, London, N1 7JQ, United Kingdom.
Registered in England & Wales. Company Registration No. 07144084.