Some sites use frames, iframes or variables parts inside a page. This is useful for programmers but it can cause usability issues for the page’s reader, if he wants to send the exact link to a friend or save it as a favorite for instance, the link would have the original URL without the internal modifications or the correct frame. To solve this, there is a trick that can be used, use the anchor part of URLs to put variables, all done with javascript.
After the jump, the code that does this. To use it:
- params.setParam(paramName,paramValue) to set a parameter
- params.getParam(paramName) to obtain what the parameter contains.
var params = {
nameList: null, // List of Params names
valueList: null, // List of Params values
anchs: null, // Initialized with the values in hash part of URL
// Next function sets a new parameter in the hash part or URL
setParam: function(param,val){
this.retrieveParams();
if(this.anchs=="")
{
location.hash = param+"/"+val;
return;
}
else
{
var urlParams = "", createNewParam = true;
for(i=0; i<this.nameList.length; i++)
{
if(this.nameList[i]==param)
{
this.valueList[i]=val;
createNewParam = false;
break;
}
}
if(createNewParam)
{
var nameTemp, valueTemp;
nameTemp = new Array(this.nameList.length+1);
valueTemp = new Array(this.nameList.length+1);
for(i=0; i<this.nameList.length; i++)
{
nameTemp[i]=this.nameList[i];
valueTemp[i]=this.valueList[i];
}
nameTemp[nameTemp.length-1]=param;
valueTemp[valueTemp.length-1]=val;
this.nameList = nameTemp;
this.valueList = valueTemp;
}
for(i=0; i<this.nameList.length; i++)
{
if(i==0)
urlParams += this.nameList[i]+"/"+this.valueList[i];
else
urlParams += "&"+this.nameList[i]+"/"+this.valueList[i];
}
location.hash = urlParams;
}
},
// Next function gets a new parameter in the hash part or URL
getParam : function(param){
this.retrieveParams();
for(i=0; i<this.nameList.length; i++)
{
if(this.nameList[i]==param)
{
return this.valueList[i];
}
}
return null;
},
// Next function is called before other functions
retrieveParams: function(){
this.nameList = null;
this.valueList = null;
this.anchs = location.hash;
if(location.href){
var paramArray = this.anchs.substr(1).split('&');
this.nameList = new Array(paramArray.length);
this.valueList = new Array(paramArray.length);
for(i=0; i<paramArray.length; i++)
{
this.nameList[i] = paramArray[i].split('/')[0];
this.valueList[i] = paramArray[i].split('/')[1];
}
}
}
};
