-
-
Save barlas/85361c39924afe3457f6 to your computer and use it in GitHub Desktop.
javascript - Detecting hash change from browser's back and foward buttons.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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