0

I need to define and to read hash values like

#page1&filter=1-1-0 
#filter=1-1-0 (if page number is omitted)
#page1 (if filter is not defined)

I.e. page number will be part of the parameter and will be without value. How to work (get and set) with such parameters?

James Allardice
  • 164,175
  • 21
  • 332
  • 312
LA_
  • 19,823
  • 58
  • 172
  • 308

2 Answers2

2

You can access the contents of the string after the hash in the URL with window.location.hash.

You'll then need to so a little bit of parsing to get your key-value pairs. Something like the code below:

function getParameters(){
    params = {}
    var keyValuePairs = window.location.hash.substr(1).split('&');
    for (x in keyValuePairs){
        var split = keyValuePairs[x].split('=', 2);
        params[split[0]] = (split[1]) ? decodeURI(split[1]) : "";
    }
    return params;
}

function setParameters(key, value){
    var params = getParameters();
    params[key] = value;
    var hashString = ""
    for (x in params){
        if (params[x]){
            hashString += "&" + x + "=" + encodeURI(params[x]);
        } else {
            hashString += "&" + x;
        }
    }
    window.location.hash = hashString.substr(1);
}

You could read the read your "filter" parameter with something like:

var parameters = getParameters();
console.log(parameters.filter);
extols
  • 1,762
  • 14
  • 19
  • Thanks, extols. Is there any way to simplify the same with jQuery BBQ plugin? ;) Also, what I don't like with your approach - if page is not defined, then hash looks like `#&filter=1-1-326` - ideally, there shouldn't be `&` sign. Can it be fixed? – LA_ Nov 06 '11 at 08:15
0

Here is the solution with BBQ plugin usage (demo):

var hash = $.deparam.fragment();
var page = 'page1';
$.each(hash, function(i, val) {
    if (i.indexOf('page') != -1) page = i;
});
var filter = (hash.filter==undefined) ? '0-0-0' : hash.filter;

// update hash
$.bbq.pushState('#' + page + '&filter=' + filter);
LA_
  • 19,823
  • 58
  • 172
  • 308