Using hash links allows for bookmarkable/sharable links to trigger JavaScript code, instead of reloading the page. Ben Almans jQuery hashchange event allows you to bind an event handler to the hashchange event, this plugin works with older browsers that don't support this normally. An event handler bound to hashchange can read the hash part of the url, and call any function.
// register event handler
function bindHashchange() {
$(window).bind('hashchange', function(event) {
event.preventDefault();
var label = location.hash.substring(1);
handleLabel(label);
});
// trigger event so handler will be run when page is opened first time
// otherwise handler will only run when clicking on hash links
$(window).trigger('hashchange');
}
// read and handle hash part of url
function handleLabel(label) {
if ( label.length > 0 ) {
// using label from url
switchPage(label);
} else {
// use the default label, if no hash link was present
switchPage('start');
}
}
// in this case, load hidden <div>'s into a <div id="content">
function switchPage(label) {
if ( label == 'start ) {
$('div#content').html($('div#start'));
} else if ( label == 'some_other_page' ) {
// do something else
}
}
This other event handler can process 2 arguments separated by a dot ('.') in the same url.
function processHash() {
var str = location.hash.substring(1);
var pos = $.inArray('.', str);
var label = '';
var arg = '';
if ( pos > -1 ) {
label = str.substring(0, pos);
} else {
label = str.substring(0);
}
if ( pos > 1 ) {
arg = str.substring(pos+1);
}
if ( label.length == 0 ) {
// the default page to open of label is empty
loadContent('start');
} else {
// load page, and pass an argument
loadContent(label, arg);
}
}
If regular expressions are used, any combination of characters can be parsed.
var registry = {};
// split on character '.'
var args = label.split(/\./g);
for ( i in args ) {
var arg = args[i];
// split on character '='
var temp = arg.split('=');
var name = temp[0];
var value = temp[1];
// store argument in registry
registry[name] = value;
}
// registry is loaded, ready to run application that depends on arguments
This will transform the url:
mysite/#company.page=items.color=red
Into the following JavaScript Object:
Object { company=undefined, page="items", color="red"}
Then it is only a matter of running jQuery's show() or hide() functions on your selected elements.
This could be transformed into non-jQuery JavaScript, but then you would lose the functionality that Ben Alman delivers, which is crucial for a portable solution.