Skip to content

Instantly share code, notes, and snippets.

@jgwhite
Created May 31, 2011 10:56
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jgwhite/1000304 to your computer and use it in GitHub Desktop.
Save jgwhite/1000304 to your computer and use it in GitHub Desktop.
Simple pushState wrapper
// 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