Showing posts with label ajax. Show all posts
Showing posts with label ajax. Show all posts

Wednesday, June 15, 2011

Hashtag Ajax using JQuery

Hashtag Ajax being more popular nowdays. Gmail, Twitter, and other modern Ajax websites applying this method in their web. So what is Hashtag Ajax?

Hashtag Ajax is an Ajax based page navigation without sacrificing SEO, browser bookmarking and back button.

So what its look like? and how it works?

Look at this following example:

http://example.com/index.html
http://example.com/about.html
http://example.com/contact.html

Instead of having those conventional URL which require browser reload when navigating each other, Hashtag ajax would use this following URL (example):

http://example.com/#!:/index.html
http://example.com/#!:/about.html
http://example.com/#!:/contact.html

Hash symbol (#) in URL commonly used as an anchor to a section of a webpage. Without javascript all above links just load the same page index.html.

Thanks to window.location.hash and JQuery ajax (or other who uses XmlHttpRequest) we can use hash to navigate pages. A simple way can do this: getting the hash value, remove the string code (in this example is #!:) and load the resulting path into JQuery.load().

I wrote a script that scan all a links with #!:[path] pattern and bind the click function using JQuery to load target pages into target div.

// call init
$(init);

function init() {
  ajax_page_handler();
  page_load($(window.location).attr("hash")); // goto first page if #!: is available
}

function page_load($href) {
  if($href != undefined && $href.substring(0, 3) == '#!:') {
    $('#content').load($href.substring(3)); // replace body the #content with loaded html
    $('html, body').animate({scrollTop:0}, 'slow'); // bonus
  }
}

/**
 * This method load #content on every url hash change
 * 
 * @return
 */
function ajax_page_handler() {
  $(window).bind('hashchange', function () {
    $href = $(window.location).attr("hash");
    page_load($href);
  });
  // this allow you to reload by clicking the same link
  $('a[href^="#!:"]').live('click', function() {
    $curhref = $(window.location).attr("hash");
    $href = $(this).attr('href');
    if($curhref == $href) {
      page_load($href);
    }
  });
}

Now, build your websites, download JQuery, and load JQury and this script inside your pages.
And then change all url to use #!:, dont forget to have main div #content as a place where content loaded and Bang!. You have a simple Ajax website.

Download the example here (http://dl.dropbox.com/u/3579854/hashtag.zip)