Search code examples
javascriptnavigation

How to implement a hash-key navigation?


I want to implement an Ajax based hash-key navigation like this:

http://www.foo.bar/#/about/
http://www.foo.bar/#/news/
http://www.foo.bar/#/products/

How can I implement this structure?


Solution

  • 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