How to implement a hash-key navigation?
Using the example you gave above, and keeping things simple, you could do the following:
function aboutHandler() {
//Do stuff--e.g. get via AJAX -> render template (optional) -> append HTML to an element
}
function newsHandler() {
//Do stuff
}
function productsHandler() {
//Do stuff
}
function locationHashChanged() {
(location.hash === "#/about/") && aboutHandler();
(location.hash === "#/news/") && newsHandler();
(location.hash === "#/products/") && productsHandler();
}
}
window.onhashchange = locationHashChanged;
With a hash-based navigation structure, you'll be defining your routes and their handlers via JS in the browser... When the hash is changed, a 'hashchange' event is fired, and the 'window.onhashchange' handler function is called.*
e.g.
if ("onhashchange" in window) {
alert("The browser supports the hashchange event!");
}
function locationHashChanged() {
if (location.hash === "#somecoolfeature") {
somecoolfeature();
}
}
window.onhashchange = locationHashChanged;
There's the option of using the more recently introduced HTML5 pushstate, too.
Check out http://www.microjs.com/#spa for some good JS routing libraries--some of them provide support for HTML5 pushstate as well as fallbacks to hashchange for older browsers.
If you're looking to build a serious application you could use something like Backbone.js to handle models, views, routing, etc. You should also check out Crossroads.js (routing library) and its accompanying Hasher.js (hashchange/pushstate library) if you don't need all the extras that come with Backbone.
...or there's LeviRoutes (HTML5 pushstate only, VERY much like routing in Express for Node.js).
...or Jquery BBQ (for Jquery/hashchange-based/some nice features -- (github.com/cowboy/jquery-bbq)
...and then, there's Director (hashchange/tons of features/works in Node.js and the browser/similar to Express routing/developed mostly by the folks at Nodejitsu).
*Note: if you're focusing on SEO, then hashchange/ajax will introduce some problems...you may want to read through Google's webmaster guidelines -- http://code.google.com/web/ajaxcrawling/docs/getting-started.html
**P.S. you can find all the abovementioned libraries on the MicroJS.com site, except for Jquery BBQ
It looks like you are developing a single page application. So, I would recommend you to use Backbone.js. Here is a code snippet for your task.
<script>
var Controller = Backbone.Router.extend({
routes: {
"/about/": "about",
"/news/": "news",
"/products/": "products"
},
about: function(){
// ...
},
news: function(){
// ...
},
products: functions(){
// ...
}
});
var controller = new Controller();
Backbone.history.start();
</script>
Backbone. What is a router?