Skip to content

Instantly share code, notes, and snippets.

@bohman
Last active March 10, 2016 10:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bohman/3ed7952fd8d3b17547bf to your computer and use it in GitHub Desktop.
Save bohman/3ed7952fd8d3b17547bf to your computer and use it in GitHub Desktop.
For those times when you need to imitate query parameters with hashes
/**
*
* When you need to use the hash to imitate query parameters,
* like so:
*
* http://whatever.man/#key=value&another_key=another_value
*
**/
// Set URL to a specific hash. It overrides any existing hash.
set_hash: function(hash_object) {
if(hash_object) {
var new_hash = '';
for (var key in hash_object) {
new_hash += key + '=' + hash_object[key] + '&';
}
window.location.hash = new_hash.slice(0, -1);
}
}
// Returns hash parts in an easy to use object
get_hash_parts: function() {
var hashes = window.location.hash.slice(window.location.hash.indexOf('#') + 1).split('&');
var hash_object = {}
for(var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
if(hash[0] && hash[1]) {
hash_object[hash[0]] = hash[1];
}
}
return hash_object;
}
// To add a key
var hash_object = get_hash_parts();
hash_object['new_key'] = 'new_value';
set_hash(hash_object);
// To remove a key
var hash_object = get_hash_parts();
delete hash_object.old_key;
set_hash(hash_object);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment