Search code examples
javascriptjqueryhashchange

How to trigger different functions on hash change based on hash value with jQuery?


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!


Solution

  • 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).