0

I want to build a basic anchor based navigation system using jQuery. I don't really want to use a plugin like this as suggested here. Can anyone help me out with the basic logic of building a system like this?

Essentially I want to be able to have one page serve up multiple ajax content via links like this:

  • /myurl.html#state1
  • /myurl.html#state2

Currently I just bind to the click handler of links to open up dialogs etc. I could then change the URL to /myurl.html#state1. The question is do I do it this way, or do I just make the <a> tags themselves point to that url and then use jQuery to detect when the URL has changed meaning itll also work on page load too?

Any suggestions / thoughts would be great - thanks

Community
  • 1
  • 1
Chris
  • 26,744
  • 48
  • 193
  • 345
  • 4
    I know you might not want to use a plugin, but I've found jquery-bbq to be the best for this kind of functionality http://benalman.com/projects/jquery-bbq-plugin/ – Calum Apr 08 '11 at 11:37
  • Sans plugin, this will be of use http://yensdesign.com/2008/11/creating-ajax-websites-based-on-anchor-navigation/ – Calum Apr 08 '11 at 11:40
  • @Calum I spotted BBQ before, thanks for the suggestion, its just for one page though so a plugin seems like overkill. I saw the yendesign post before as well but I really dont like the idea of setting a timer to check for changes - seems wasteful – Chris Apr 08 '11 at 12:25
  • 1
    @Chris, why re-invent the wheel? BBQ has a small foot print and supports everything you seem to be looking for and more out of the box. – Sergei Golos Apr 08 '11 at 13:08
  • @Chris - I agree with everyone here... Go with the plugin. – webdad3 Apr 08 '11 at 13:14
  • 1
    I want to do this because of two reasons: 1. This is going into an embedded system where the use of external plugins is hard to get sanctioned and footprint is an issue. 2. I want to learn :) – Chris Apr 08 '11 at 13:32
  • +1 for wanting to learn lol most people want the code copy and paste don't want to change anything, but well done for trying – Val Apr 08 '11 at 13:54

1 Answers1

2
<a href="#state1" rel="ajaxpage1.html"></a>
<a href="#state2" rel="ajaxpage2.html"></a>

$('a').each(function (i,obj){
   $(obj).click(function (){
       var url = $(obj).attr('rel');
       $..ajax({
          url: url,
          success: function (){...},
          error : function (){...}// incase you get a 404, or 500 and so on....
       });
   });
});

$(document).ready(function (){
   //if you need it on refresh, or if a user got the link from another page
   // it automatically will trigger the click therefore trigger the ajax
   if(window.location.hash != '#'){
      $('a[href="'+window.location.hash+'"]').click();
   }
});

I still thing you should use a plugin, as they have had bugs, and fixed them probably so you would have to test your thing, waste alot of time but your call :)

Val
  • 17,336
  • 23
  • 95
  • 144