jQuery Get URL Variables

August 18, 2011
Posted By
jquery-geturlvar-example.jpg

Send & Read URL Variables Using jQuery getUrlVar

jQuery getUrlVar is a tiny piece of jQuery plugin that does wonderful job by reading the URL Variables. Sometimes you may need to read your own custom url variables and do changes on the other pages.

jQuery getUrlVar Plugin

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 jQuery.getUrlVars()[name];
  }
});

You can download the script here

How to use jQuery getUrlVars

if($.getUrlVars()['profileId'])
{
  alert($.getUrlVars()['profileId'][0]);
}

Example on Healthy Families BC Walking Challenge

Healthy Families BC Walking Challenge Popup

The goal to use query getUrlVar is to show the Lumby popup when users land on the page. What we did is to pass a URL variable 'profileId'. We use getUrlVar to read the id and do the trick. It's very useful when it comes to the REAL WORLD

Before: http://www.healthyfamiliesbcwalkingchallenge.ca/Lumby

After: http://www.healthyfamiliesbcwalkingchallenge.ca/Lumby?profileId=8642