Oliver Spryn
Oliver Spryn

Reputation: 17368

jQuery Anchor Based Navigation

I am looking for a way to navigate between pages and respond to events when the anchor changes with jQuery. In order to illustrate my question, let me demonstrate with an example:

  1. A user enters a page which has loaded jQuery, without the jQuery UI or any additional plugins.
  2. As the page loads, the user is redirected from http://thesite.com/ to http://thesite.com/#/, without any page refresh.
  3. A link, like this, is clicked: <a href="#/author/bio">My Bio</a>.
  4. jQuery uses the $.ajax() method to load the requested page, without a page refresh.
  5. The user clicks the browser back button, and goes to http://thesite.com/#/, without a page refresh.

I am good when it comes to loading the page content. However, here is what I don't know:

  1. How do I redirect to http://thesite.com/#/, if it is not supplied when the page loads?
  2. How do I listen for a request to load a page without a refresh, when a link with an anchor divider (#) is clicked?
  3. Most importantly, how do I listen for browser back/forward requests, the know what page to load?

Sorry for the crash list of questions. If my scenario wasn't clear enough, then here is a great site that already does it: http://grooveshark.com/.

Thank you for your time! I will reward generously for thorough answers/comments.

Upvotes: 0

Views: 2317

Answers (2)

Dileep
Dileep

Reputation: 775

First load jquery.

on ready change all urls something like

$('a').forEach(function(obj){
   obj.href=obj.href+"#";
});
// on click load 
$('a').click(function(a){
   ajaxLoad(a);

//push to window.history

});

Upvotes: -1

Naftali
Naftali

Reputation: 146350

Well you would have to add an onclick to the a tags.

Then all you have to do is:

$('a').click(function(){

    window.location.hash = this.href;
    //some load of that url to the page
    return false;

});

And to listen in on hash changes you need a plugin like this one

Upvotes: 3

Related Questions