A simple jQuery parameter extractor.

Some times you need to get parameters from the URL client site... It is not something that is done often but when I come across the urge... I just do not remember how I did it last time.

Here is a simple extent you put in an isolated JS file or just in a Script tag on the same page; Then call it using a jQuery like feel. (Does not conflict with jQuery)


$.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});


(/contact.html?phone=SomeContentHere)
and then you can simply use it within JS scope like this, 


var phone = $.getUrlVar('phone');
if ( phone == undefined) { alert('I need your phone bro!'); } else { alert('Thanks!'); }



Comments