# Getting a URL Parameter
A function that you give it the param, (url params or url args, whatever you want to call it) to find from the current url (key), and she returns the value of that parameter.
var getUrlParameter = function getUrlParameter(sParam) { var sPageURL = decodeURIComponent(window.location.search.substring(1)), sURLVariables = sPageURL.split('&'), sParameterName, i; for (i = 0; i < sURLVariables.length; i++) { sParameterName = sURLVariables[i].split('='); if (sParameterName[0] === sParam) { return sParameterName[1] === undefined ? true : sParameterName[1]; } } }; var area = getUrlParameter(‘area'); // get area value. if (typeof area == 'undefined') { // do something it exists! } else { // cry me a river }
# Setting a URL Parameter (or changing it)
Sometimes it is handy to change (or add ) a url parameter, from JavaScript
This function that you give it a : key (kuku) and a value (..value) and she updates the appropriate key, if dosen’t exists, she creates it.
the function doesn’t touch other parameters (leave them like they were).
I used it in a situation where it was needed to check a parameter called “killme”
if killme value was given to the function, she will delete the appropriate value.
note: if killme sent when their is no such parameter, she creates it with this value.
// added 'killme' value - to remove the query var alltogether. function setGetParameter(paramName, paramValue) { var url = window.location.href; if (url.indexOf(paramName + "=") >= 0) { var prefix = url.substring(0, url.indexOf(paramName)); var suffix = url.substring(url.indexOf(paramName)); suffix = suffix.substring(suffix.indexOf("=") + 1); suffix = (suffix.indexOf("&") >= 0) ? suffix.substring(suffix.indexOf("&")) : ""; if (paramValue == 'killme') { url = prefix + suffix; } else { url = prefix + paramName + "=" + paramValue + suffix; } } else { if (url.indexOf("?") < 0) url += "?" + paramName + "=" + paramValue; else url += "&" + paramName + "=" + paramValue; } window.location.href = url; }
usage :
// Handles click jQuery( ‘.page-templat-page-something.area-widget li a' ).click(function( event ) { event.preventDefault(); var href = jQuery(this).attr(‘href'); //get the a href if (typeof location != 'undefined' || href !='killme') { // check if location exists and if the value is not kill // .. killme request (because if kill and doesn’t exists ->when try to kill error, this fix that) setGetParameter('area',href); } });