Skip to content

Instantly share code, notes, and snippets.

@sstephenson
Created December 13, 2010 21:55
Show Gist options
  • Star 54 You must be signed in to star a gist
  • Fork 11 You must be signed in to fork a gist
  • Save sstephenson/739659 to your computer and use it in GitHub Desktop.
Save sstephenson/739659 to your computer and use it in GitHub Desktop.
How to detect whether a hash change came from the Back or Forward button
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") }
));
@tdd
Copy link

tdd commented Feb 2, 2011

Hey Sam,

Quick question: any specific reason why you went with "hashHistory = hashHistory.slice(0, -1);" instead of just "hashHistory.pop()"?!

@sstephenson
Copy link
Author

Nope, that sure could be pop().

@tdd
Copy link

tdd commented Feb 2, 2011

Ha, good :-) I was wondering whether you had some super-intricate reason here :-) And btw, again: major props on Basecamp Mobile. I'm dying to pick your brain on the tech side of it :-)

@xu33
Copy link

xu33 commented May 9, 2013

There is something wrong when the history.length reach 50,it won't increase any more.

@7cc
Copy link

7cc commented Jun 11, 2013

a -> #b -> #a -> back

now location.hash is #b

then
forward ... console.log back
back ... console.log back

@barlas
Copy link

barlas commented Nov 25, 2014

really nice method to play with hashes, thanks mate !

@fabriciopa
Copy link

Works like a charm! Thanks a lot!

@N02870941
Copy link

Beautiful, thanks so much. I am writing an angular app, and all that ui.router stuff is so complicated, This is literally all I needed! I know I shouldn't be mixing frameworks, etc, but it was too painful. Thanks!!

@itgoldman
Copy link

as mentioned by 7cc, this fails: a -> #b -> #a -> back
it also fails if you refresh the page in the middle of history and then press forward or back. this is because you can't tell index of your current history within the actual browser history array - therefore can't tell if next hashchange is forward or backwards (even if all hashes are unique).
so my conclusion: this is a problem impossible to solve.

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