Skip to content

Instantly share code, notes, and snippets.

@unbug
Forked from sstephenson/back_forward.js
Created March 15, 2014 05:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save unbug/9562211 to your computer and use it in GitHub Desktop.
Save unbug/9562211 to your computer and use it in GitHub Desktop.
var detectBackOrForward = function(onBack, onForward) {
hashHistory = [window.location.hash];
historyLength = window.history.length;
return function() {
var hash = window.location.hash, length = window.history.length;
if (hashHistory.length && historyLength == length) {
if (hashHistory[hashHistory.length - 2] == hash) {
hashHistory = hashHistory.slice(0, -1);
onBack();
} else {
hashHistory.push(hash);
onForward();
}
} else {
hashHistory.push(hash);
historyLength = length;
}
}
};
window.addEventListener("hashchange", detectBackOrForward(
function() { console.log("back") },
function() { console.log("forward") }
));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment