2

I'm using Ben Alman's jQuery hashChange event plugin. the hash part looks like this:

#x=1&y=2&z=3

I already have functions that parse it getHashPart(key) and setHashPart(key).

I would like to have a function that would allow to register with the change of only a specific part of the hash. I would use it as such (I guess...):

$(window).hashchange('x',function(new_value_of_x) {do something x related;});
$(window).hashchange('y',function(new_value_of_y) {do something y related;});

How would I register such a function with jQuery? anything similar exists?

Thanks!

Ben
  • 10,020
  • 21
  • 94
  • 157
  • 1
    http://www.bennadel.com/blog/1520-Binding-Events-To-Non-DOM-Objects-With-jQuery.htm explains how you can setup an onchange event for the url of the page. However, if you are doing what I think you are doing, you should bind the links which set the hash to perform what you want it to do, and then on document load check if there was any hash in the url to perform the action it should. – Niklas May 30 '11 at 10:05
  • Good article. I'll hold on to see other proposed solutions. – Ben May 30 '11 at 11:57
  • 1
    ps. If I were you, I'd change the title of the question to something like "How to trigger different functions on hash change based on hash value with jQuery?". Just an offer. – Ege Özcan May 30 '11 at 15:24

1 Answers1

4

You can have a function that responds to all hashchange events (preferably keeping the hashchange plugin in use), then redirect to individual handlers like this:

var hashParameters = {};

$(window).bind("hashchange",function(event) {
//if you're using the awesome hashchange plugin
//$(window).hashchange(function(event) { ...
    var newParameters = getParameters(event.target.location.hash.substring(1));
    $.each(newParameters, function(key, value) {
       if(hashParameters[key] !== value) $(window).trigger(key + "-change");
       hashParameters[key] = value;
    });
});

$(window).bind("andsome-change", function() {
    alert("hi!");
});

function getParameters(paramString) {
    //taken from http://stackoverflow.com/questions/4197591/parsing-url-hash-fragment-identifier-with-javascript/4198132#4198132
    var params = {};
    var e, a = /\+/g, r = /([^&;=]+)=?([^&;]*)/g,
        d = function (s) { return decodeURIComponent(s.replace(a, " ")); };
    while (e = r.exec(paramString))
       params[d(e[1])] = d(e[2]);
    return params;
}

window.location.hash = "some=value&andsome=othervalue";

I have a working demo here (now with hashchange plugin, see first comment).

Ege Özcan
  • 13,971
  • 2
  • 30
  • 51
  • 1
    +1, fyi, you *can* include external scripts in a jsFiddle - on the left click "Add Resources" and paste the link in. Alternatively, just stick `` in the HTML frame. – Thomas Shields May 30 '11 at 15:07
  • that "I couldn't" means "I was just too lazy" too =)) thanks a lot for the suggestion and here is link with the fix: http://jsfiddle.net/TuVBL/1/ – Ege Özcan May 30 '11 at 15:12