Last active
August 29, 2015 14:05
-
-
Save schonert/1d00d2ed05c2876bad33 to your computer and use it in GitHub Desktop.
Update location search parameter
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
/** | |
* 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; | |
}; |
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
/** | |
* 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