Skip to content

Instantly share code, notes, and snippets.

@sstephenson
Created December 13, 2010 21:55

Revisions

  1. sstephenson created this gist Dec 13, 2010.
    25 changes: 25 additions & 0 deletions back_forward.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,25 @@
    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") }
    ));