-
-
Save sstephenson/739659 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") } | |
)); |
Nope, that sure could be pop()
.
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 :-)
There is something wrong when the history.length reach 50,it won't increase any more.
a -> #b -> #a -> back
now location.hash is #b
then
forward ... console.log back
back ... console.log back
really nice method to play with hashes, thanks mate !
Works like a charm! Thanks a lot!
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!!
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.
Hey Sam,
Quick question: any specific reason why you went with "hashHistory = hashHistory.slice(0, -1);" instead of just "hashHistory.pop()"?!