Element.fromQueryString(), Window.fromQueryString(), String.fromQueryString()

Snippets are small pieces of code that do not fit in the UvumiTools plugin category. Please note that each of these semi-useful functions requires Mootools 1.2.

Does the opposite of Mootools' toQueryString() function: generates a Hash from an URL with a query string. The Hash will contain an entry for each parameter of the query string. The function can be applied to:

If the element/window/string does not contain any parameters, the function will return false.

Native.implement([Element,Document,Window,String],{
fromQueryString : function(){
switch($type(this)){
case 'window':
case 'document':
var url = location.href;
break;
case 'element':
switch(this.get('tag')){
case 'a':
var url = this.get('href');
break;
case 'form':
var url = this.get('action');
break;
default:
return false;
}
break;
case 'string':
var url = this;
break;
default:
return false;
}
var parameters = false;
if(url.contains('?')){
if(url.contains('#')){
url = url.split('#')[0];
}
var query = url.split('?')[1];
if(query != ""){
var parameters = new Hash();
params = query.split('&');
params.each(function(param){
param = param.split('=');
parameters.set(param[0],param[1]);
});
}
}
return parameters;
}
});

Usage:

$('myLink').fromQueryString();         //returns a Hash with the parameters of that link
window.fromQueryString();              //returns a Hash containing the parameters of the current page
"snippets.html".fromQueryString();     //returns False
var params = "snippets.html?fruit=apple&animal=cat".fromQueryString();     //store the paramters in 'params'
alert(params.get('animal'));           //alerts 'cat'

Demo: http://uvumitools.com/snippets.html?snippet=querystring&fruit=apple&animal=cat#foo

In this demo, we simply stop the click event on that link, call the function on it, and alert the resulting Hash. Just click the link and you'll see. Notice how the 'foo' after the '#' is dropped.