Skip to content

Instantly share code, notes, and snippets.

@almonk
Forked from jgwhite/with-history.js
Created May 31, 2011 11:02
Show Gist options
  • Save almonk/1000309 to your computer and use it in GitHub Desktop.
Save almonk/1000309 to your computer and use it in GitHub Desktop.
Simple pushState wrapper
$(document).bind("WithHistory.urlDidChange", function() {
$.ajax(window.withHistory.url(), {
dataType: "html",
success: function(response) {
var body = response.match(/<body.*?>([\s\S]+?)<\/body>/)[1];
var tmp = $("<div />");
tmp.html(body);
var newContent = tmp.find("#pagecontent").html();
$("#pagecontent").animate({ opacity: 0 }, 250);
$("html, body").animate({ scrollTop: 0}, 250, function() {
$("#pagecontent").html(newContent).animate({ opacity: 1 }, 500);
});
}
})
});
window.withHistory = new WithHistory();
$("a.ajax").live("click", function(event) {
event.preventDefault();
event.stopPropagation();
window.withHistory.pushState($(this).attr("href"));
});
// WithHistory v1.0.0
// hello@withassociates.com
//
// Usage:
// $(document).bind('WithHistory.urlDidChange', function() { ... });
// window.withHistory = new WithHistory();
// window.withHistory.pushState(newUrl) // push new url
// window.withHistory.url(); // get current url
var WithHistory = function() {
this.init = function() {
if (this.supportsHistoryPushState()) {
$(window).bind('popstate', $.proxy(this, 'onPopState'));
} else {
this.hashCheckInterval = setInterval($.proxy(this, 'onCheckHash'), 200);
}
},
this.pushState = function(url) {
if (this.supportsHistoryPushState()) {
window.history.pushState('', '', url);
} else {
this.previousHash = '#' + url;
document.location.hash = url;
}
this.urlDidChange();
},
this.supportsHistoryPushState = function() {
return ('pushState' in window.history) &&
window.history['pushState'] !== null;
},
this.onCheckHash = function() {
if (document.location.hash != this.previousHash) {
this.previousHash = document.location.hash;
this.urlDidChange();
}
},
this.onPopState = function() {
this.receivedPopState = true;
this.urlDidChange();
},
this.urlDidChange = function(path) {
$(document).trigger('WithHistory.urlDidChange');
},
this.url = function() {
if (this.supportsHistoryPushState()) {
return document.location.pathname;
} else {
return document.location.hash.slice(1);
}
}
this.init();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment