Skip to content

Instantly share code, notes, and snippets.

Created March 7, 2011 04:58
  • Star 47 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Ajaxify a Website using the HTML4 HashChange Functionality
// Prepare our Variables
document = window.document,
$ = window.jQuery;
// Wait for Document
// Prepare Variables
$content = $('#content'),
$body = $(document.body),
rootUrl = document.location.protocol+'//'+(document.location.hostname||;
// Ajaxify our Internal Links
$.fn.ajaxify = function(){
// Ajaxify internal links
var $this = $(this), url = $this.attr('href'), title = $this.attr('title')||null, relativeUrl = $(this).attr('href').replace(rootUrl,'');
document.location.hash = relativeUrl;
return false;
// Chain
return this;
// Ajaxify Page
// Hook into State Changes
// Prepare
relativeUrl = '/'+document.location.hash.replace(/^\//,''),
fullUrl = rootUrl+relativeUrl;
// Set Loading
// Start Fade Out
// Ajax Request the Traditional Page
// Find the content in the page's html, and apply it to our current page's content
if ( $content.ScrollTo||false ) $content.ScrollTo(); //
// Inform Google Analytics of the change
if ( typeof pageTracker !== 'undefined' ) {
}); // end get
}); // end onStateChange
}); // end onDomLoad
})(window); // end closure
Copy link

balupton commented Mar 7, 2011

Copy link

yemster commented Jan 19, 2012

Great work Benjamin - its been incredibly useful.

In case its useful to someone else, 2 generic changes I had to make to the gist:

On line #38: should also strip out leading # from the location.hash as it's not passed to the server resulting in an incomplete url being sent


relativeUrl = '/'+document.location.hash.replace(/^\//,'')


relativeUrl = '/'+document.location.hash.replace(/^\//,'').replace(/^#/,'')

and a typo on line #48: the ajax request should be using fullUrl instead of url so it becomes

// Ajax Request the Traditional Page 

Copy link

You don't need to wrap this with $ in jQuery plugins, this is already the jQuery collection.


Can be


Copy link

well , i don't know why the $.fn.find doesn't work for me . i use the jQuery JavaScript Library v1.6.1


i try to use $.fn.filter() and it works.hope to help someone...


Copy link

cjramki commented Nov 14, 2013

how to use this plugin to browser back button.
could please help me to solve this issue

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment