Last active
August 29, 2015 14:01
-
-
Save CarlosBonetti/751e341503082a7b6c89 to your computer and use it in GitHub Desktop.
UrlHash
This file contains hidden or 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
/** | |
* Provides method to dynamically read and modify url hash params like query strings (e.g. #year=2014&month=1) | |
*/ | |
var UrlHash = { | |
/** | |
* Returns the full URL Hash, ommiting the # symbol | |
*/ | |
getHash: function () { | |
return window.location.hash.replace("#", ""); | |
}, | |
/** | |
* Set a new URL Hash | |
*/ | |
setHash: function (string) { | |
window.location.hash = string; | |
}, | |
/** | |
* Returns a new array containing all the hash parameters | |
* Example: given the url '#year=2014&month=2', UrlHash.getParams() | |
* shall return { year: "2014", month: "2" } | |
*/ | |
getParams: function () { | |
var params = {}, | |
match, | |
search = /([^&=]+)=?([^&]*)/g, | |
query = UrlHash.getHash(); | |
while (match = search.exec(query)) | |
params[match[1]] = match[2]; | |
return params; | |
}, | |
/** | |
* Sets a new Hash given the object parameter | |
* Example: UrlHash.setParams({ id: 2, title: "Lorem" }) will set the URL Hash to #id=2&title=Lorem | |
*/ | |
setParams: function (params) { | |
var queries = []; | |
for (key in params) { | |
queries.push(key + "=" + params[key]); | |
} | |
return UrlHash.setHash(queries.join("&")); | |
}, | |
/** | |
* Returns a value, given the key | |
* Example: given the url '#year=2014&month=2', UrlHash.get("year") shall return 2014 | |
* Returns the default_val param if the key does not exist | |
*/ | |
get: function (key, default_val) { | |
var params = UrlHash.getParams(); | |
return params[key] ? params[key] : default_val; | |
}, | |
/** | |
* Set a new Hash key and value | |
*/ | |
set: function (key, value) { | |
var params = UrlHash.getParams(); | |
params[key] = value; | |
return UrlHash.setParams(params); | |
}, | |
/** | |
* Erases the URL Hash | |
*/ | |
clear: function () { | |
UrlHash.setHash(""); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment