Skip to content

Instantly share code, notes, and snippets.

@hokaccha
Created February 23, 2011 07:56
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save hokaccha/840151 to your computer and use it in GitHub Desktop.
Save hokaccha/840151 to your computer and use it in GitHub Desktop.
Page transition jQuery plugin, useing history.pushState.
/*
* jquery.smarthistory.js
*
* Copyright (c) 2010 Kazuhito Hokamura
* Licensed under the MIT License:
* http://www.opensource.org/licenses/mit-license.php
*
* @author Kazuhito Hokamura (http://webtech-walker.com/)
* @version 0.0.1
*
* Page transition jQuery plugin, using history.pushState.
*
*/
(function($) {
$.fn.smarthistory = function(opt) {
if ( !('pushState' in history) ) {
return this;
}
opt = $.extend({
target: '',
defaultData: '',
cache: true,
before: function() {},
change: function() {}
}, opt);
window.addEventListener('popstate', function(event) {
var state = event.state || {};
var data = state.data;
if (data) {
opt.change(data, event);
}
else {
history.replaceState({data: opt.defaultData}, null, null);
}
});
var cache = {};
return this.live('click', function(event) {
event.preventDefault();
var $elem = $(this);
var target = $.isFunction(opt.target) ? opt.target.call(this) : opt.target;
var href = $elem.attr('href');
opt.before.call(this);
if (opt.cache && target in cache) {
opt.change(cache[target]);
history.pushState({data: cache[target]}, href, href);
}
else {
$.get(target)
.done(function(data) {
opt.change(data);
history.pushState({data: data}, href, href);
if (opt.cache) {
cache[target] = data;
}
})
.fail(function() {
location.href = target;
});
}
});
};
})(jQuery);
@tokuhirom
Copy link

s/useing/using/ ?

@hokaccha
Copy link
Author

hokaccha commented Jul 6, 2011

yes! thanks!

@BeetleTN
Copy link

How use it ?

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