Created
February 23, 2015 13:39
-
-
Save Rycochet/78072cfec31829183f71 to your computer and use it in GitHub Desktop.
Use window.history easily via jQuery
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
/** | |
* Levarage the wnidow.history object for AJAX website navigation | |
* @param {(Function|String|Number|null)} arg Use a function(url,isPop) to set the callback, a string for a url, and a number for a relative history url, finally "null" returns the current url | |
*/ | |
$.pushState = function(arg) { | |
var state = $.pushState; | |
if (state.index === undefined) { | |
var url = window.location.href; | |
state.index = 0; | |
state.state = [url]; | |
state.callback = $.noop; | |
state.event = function(event) { | |
var index = (event.state || {}).index; | |
if (Number.isInteger(index)) { | |
var url = state.state[state.index = index] = event.state.url; | |
state.callback(url, false); | |
return false; | |
} | |
}; | |
window.history.replaceState({ | |
index: 0, | |
url: url | |
}, "", url); | |
window.addEventListener("popstate", state.event, false); | |
} | |
if (typeof arg === "function") { | |
state.callback = arg; | |
return true; | |
} else if (typeof arg === "string") { | |
if (arg[0] === "#") { | |
arg = state.state[state.index].replace(/(^.*\/|#.*$)/g, "") + arg; | |
} | |
if (window.history) { | |
window.history.pushState({ | |
index: ++state.index, | |
url: arg | |
}, "", arg); | |
} else { | |
window.location.href = arg; | |
} | |
state.state[state.index] = arg; | |
state.callback(arg, false); | |
return true; | |
} else if (typeof arg === "number") { | |
return state.state[arg >= 0 ? arg : state.index + arg] || ""; | |
} else if (arg === null) { | |
return state.state[state.index]; | |
} | |
return false; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment