Skip to content

Instantly share code, notes, and snippets.

@schonert
Last active August 29, 2015 14:05
Show Gist options
  • Save schonert/1d00d2ed05c2876bad33 to your computer and use it in GitHub Desktop.
Save schonert/1d00d2ed05c2876bad33 to your computer and use it in GitHub Desktop.
Update location search parameter
/**
* Get search parameters as an object.
* Pasing a key will return the givin value
*/
var getSearch = function(key) {
var search = location.search.trim().slice(1).split('&'),
params = {};
// Split search into an paras obj
while(search.length) {
var param = search.shift().split('=');
// Make sure properties has a key
if(param[0]) {
params[param[0]] = param[1];
}
}
return key ? params[key] : params;
};
/**
* Updates a query key, using pushState,
* without replacing the rest of the query parameters
*/
var updateSearch = function(key, value) {
if(history.pushState){
var params = getSearch(),
query = '';
// Set the key => val
params[key] = encodeURIComponent(value);
// Rebuild search
for(var param in params) {
// Only add param if it has a value
if(params[param]) {
query += query.length ? '&' : '?';
query += param + '=' + params[param];
}
}
history.pushState(null, null, query);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment