Skip to content

Instantly share code, notes, and snippets.

@CWSpear
Forked from balupton/README.md
Created July 8, 2012 05:16
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save CWSpear/3069522 to your computer and use it in GitHub Desktop.
Save CWSpear/3069522 to your computer and use it in GitHub Desktop.
Ajaxify a Website with the HTML5 History API using History.js, jQuery and ScrollTo

This gist will ajaxify your website with the HTML5 History API using History.js and ScrollTo.

This is my (CWSpear's) version. It applies a sweeeeeet slide transition that makes the world awesome. Check it out in action on http://cameronspear.com.

Note that it DOES change the DOM by wrapping the target in a special div, but this is by far the easiest way to make this work for 99% of cases (as long as something else isn't affected by a slightly different DOM).

Installation

<!-- jQuery --> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> 
 
<!-- jQuery ScrollTo Plugin -->
<script defer src="http://balupton.github.com/jquery-scrollto/scripts/jquery.scrollto.min.js"></script>

<!-- History.js --> 
<script defer src="http://balupton.github.com/history.js/scripts/bundled/html4+html5/jquery.history.js"></script>

<!-- This Gist -->
<script defer src="http://gist.github.com/raw/854622/ajaxify-html5.js"></script>  

Explanation

What do the installation instructions do?

  1. Load in jQuery
  2. Load in the jQuery ScrollTo Plugin allowing our ajaxify gist to scroll nicely and smoothly to the new loaded in content
  3. Load in History.js with support for jQuery, HTML4 and HTML5
  4. Load in this gist :-)

What does this gist do?

  1. Check if History.js is enabled for our current browser, if it isn't then skip this gist.

  2. Create a way to detect our page's root url, so we can compare our links against it.

  3. Create a way to convert the ajax repsonse into a format jQuery will understand - as jQuery is only made to handle elements which go inside the body element, not elements made for the head element.

  4. Define our content and menu selectors, these are using when we load in new pages. We use our content selector to find our new content within the response, and replace the existing content on our current page. We use our menu selector to update the active navigation link in our menu when the page changes.

  5. Discover our internal links on our website, and upgrade them so when they are clicked it instead of changing the page to the new page, it will change our page's state to the new page. Links with the class no-ajaxy will not be upgraded.

  6. When a page state change occurs, we will:

    1. Determine the absolute and relative urls from the new url

    2. Use our content selector to find our current page's content and fade it out

    3. Send off an ajax request to the absolute url

    4. Convert the response into one we can undertand

    5. Extract the response's title and set document.title and the title element to it

    6. Use our menu selector to find our page's menu, then scan for new page's url in the menu, and make that the active menu item and mark other menu items inactive

    7. Finish the current content's fadeout animation

    8. Use our menu selector to find the new page's content, and replace the current content with the new page's content

    9. Fade the new content in

    10. Scroll to the new current content so the user is directed to the right place - rather than them ending up looking at the footer or something instead of your page's content due to the height shift with the content change

    11. Inform Google Analytics and other tracking software about the page change

Using this Gist?

Post your website in the showcase here!

Further Reading

// https://gist.github.com/3069522
;(function($, window, document, undefined) {
// Prepare our Variables
var History = window.History;
// Check to see if History.js is enabled for our Browser
if (!History.enabled) {
return false;
}
// Wait for Document
$(document).ready(function() {
// Prepare Variables
var
/* Application Specific Variables */
contentSelector = '#main',
$historyWrapper = $(contentSelector).wrap('<div id="history-wrapper" style="position:relative;overflow:hidden;" />').parent(),
$content = $historyWrapper.filter(':first'),
contentNode = $content.get(0),
$menu = $('#menu'),
activeClass = 'selected',
activeSelector = '.selected',
menuChildrenSelector = '> ul > li > a',
/* Application Generic Variables */
$body = $(document.body),
rootUrl = History.getRootUrl(),
scrollOptions = {
duration: 800,
easing:'swing'
};
// Ensure Content
if($content.length === 0) {
$content = $body;
}
// Internal Helper
$.expr[':'].internal = function(obj, index, meta, stack) {
// Prepare
var
$this = $(obj),
url = $this.attr('href') || '',
isInternalLink;
// Check link
isInternalLink = url.substring(0, rootUrl.length) === rootUrl || url.indexOf(':') === -1;
// Ignore or Keep
return isInternalLink;
};
// HTML Helper
var documentHtml = function(html) {
// Prepare
var result = String(html)
.replace(/<\!DOCTYPE[^>]*>/i, '')
.replace(/<(html|head|body|title|meta|script)([\s\>])/gi,'<div class="document-$1"$2')
.replace(/<\/(html|head|body|title|meta|script)\>/gi,'</div>')
;
// Return
return result;
};
// Ajaxify Helper
$.fn.ajaxify = function() {
// Prepare
var $this = $(this);
// Ajaxify
$this.find('a:internal:not(.no-ajaxy, .fancybox)').click(function(event){
// Prepare
var
$this = $(this),
url = $this.attr('href'),
title = $this.attr('title') || null;
// Continue as normal for cmd clicks etc
if(event.which === 2 || event.metaKey) return true;
var stateObj = {transition: 1};
if($this.data('transition') === 'backwards' || $this.attr('rel') === 'prev') {
stateObj.transition = -1;
}
// Ajaxify this link
History.pushState(stateObj, title, url);
event.preventDefault();
return false;
});
// Chain
return $this;
};
// Ajaxify our Internal Links
$body.ajaxify();
// Hook into State Changes
$(window).bind('statechange', function() {
// Prepare Variables
var
State = History.getState(),
url = State.url,
relativeUrl = url.replace(rootUrl, '');
// Set Loading
$body.addClass('loading');
// Ajax Request the Traditional Page
$.ajax({
url: url,
success: function(data, textStatus, jqXHR) {
// Prepare
var
$data = $(documentHtml(data)),
$dataBody = $data.find('.document-body:first'),
$dataContent = $dataBody.find(contentSelector).filter(':first'),
$menuChildren, contentHtml, $scripts;
// Fetch the scripts
$scripts = $dataContent.find('.document-script');
if($scripts.length) {
$scripts.detach();
}
// Fetch the content
contentHtml = $dataContent.html() || $data.html();
if(!contentHtml) {
document.location.href = url;
return false;
}
var offScreen = $(document).width();
if(typeof State.data.transition !== 'undefined') offScreen *= State.data.transition;
// Update the menu
$menuChildren = $menu.find(menuChildrenSelector);
$menuChildren.filter(activeSelector).removeClass(activeClass);
$menuChildren = $menuChildren.has('a[href^="' + relativeUrl + '"], a[href^="/'+relativeUrl+'"], a[href^="'+url+'"]');
if($menuChildren.length === 1) $menuChildren.addClass(activeClass);
//swap out content with slide effect.
var
$oldContent = $content.find(contentSelector),
$newContent = $dataContent,
width = $oldContent.width();
$newContent.appendTo($historyWrapper).width(width).css({left: offScreen, position: 'absolute', top: 0});
// slide out old content
$oldContent.width(width).css({position: 'absolute', left: 0, top: 0}).animate({left: (-1 * offScreen)}, 800);
$newContent.html(contentHtml).ajaxify().animate({left: 0}, 800, function() {
var $this = $(this);
$oldContent.remove();
$this.removeAttr('style');
// $this.css({position: 'relative', left: 'auto', top: 'auto', width: 'inherit'});
$historyWrapper.css('height', 'auto');
// Update the title
document.title = $data.find('.document-title:first').text();
try {
document.getElementsByTagName('title')[0].innerHTML = document.title.replace('<','&lt;').replace('>','&gt;').replace(' & ',' &amp; ');
}
catch (Exception) { }
// Add the scripts
$scripts.each(function(){
var $script = $(this), scriptText = $script.text(), scriptNode = document.createElement('script');
scriptNode.appendChild(document.createTextNode(scriptText));
contentNode.appendChild(scriptNode);
});
// Complete the change
// if($body.ScrollTo || false) $body.ScrollTo(scrollOptions); // http://balupton.com/projects/jquery-scrollto
$body.removeClass('loading');
// Inform Google Analytics of the change
if(typeof window._gaq !== 'undefined') {
window._gaq.push(['_trackPageview', relativeUrl]);
}
// Inform ReInvigorate of a state change
if(typeof window.reinvigorate !== 'undefined' && typeof window.reinvigorate.ajax_track !== 'undefined') {
window.reinvigorate.ajax_track(url);
// ^ we use the full url here as that is what reinvigorate supports
}
}); // end animation
// TODO: fix this stupid thing! $newContent's height is wrong here
$historyWrapper.height(Math.max($oldContent.outerHeight(true), $newContent.outerHeight(true)));
// console.log($oldContent.outerHeight(true), $newContent.outerHeight(true));
},
error: function(jqXHR, textStatus, errorThrown){
document.location.href = url;
return false;
}
}); // end ajax
$.fn.outerHTML = function() {
return $(this).clone().wrap('<div></div>').parent().html();
};
}); // end onStateChange
// some reason, IE isn't restoring states from hash tag
if($.browser.msie) {
$(window).trigger('statechange');
}
}); // end onDomLoad
})(jQuery, this, this.document); // end closure
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment