Archive

bind events to hash changes in JavaScript

I have been using pieces of this function for a while, and finally put it together in one comprehensive piece. This is the what it does: sets event listener on the "hash" including a default on-load state. So here is the function:

  var bindHash = function(event, defaultHash, stopTime) {
    
    var getHashValue = function() {

      var hashValue = window.location.hash.substring(1);

      if (typeof hashValue == "undefined") {
        return false;
      }
      
      // Kills query string params.
      var hashLen = hashValue.indexOf("?");
      if (hashLen > 0) {
        hashValue = hashValue.substring(0, hashLen);
      }
      return hashValue;

    };
    
    // On hash change listerner
    var onHashChange = function(event, stopTime) {

      //last hash
      var lastHash = getHashValue();

      var i = setInterval(function() {
        var hash = getHashValue();

        if (hash !== lastHash) {
          event(hash);
          lastHash = hash;
        }
      }, 100);

      // Allows for "expiring" has listerner (needed for testing purposes).
      if (stopTime > 0) {

        setTimeout(function() {

          clearInterval(i);

        }, stopTime);

      }

    };

    // Inits.
    var hashValue = getHashValue();

    // Set default hash if not specified.
    if (hashValue === "" || typeof hashValue == "undefined") {
      hashValue = defaultHash;
      
      // Set hash in the url.
      window.location.hash = defaultHash;
    }

    // Run event for the first time.
    event(hashValue);

    // Bind event to hash changes
    onHashChange(event, stopTime)


  };

And here is how you can implement it. This will load JavaScript file based on the hash parameter:

  bindHash(function(hash) {

    $.getScript("/js/" + hash + ".js", function(d) {

    });

  }, "5", 0);

The first parameter is the function that fires when the hash changes, second parameter is the default hash value that is set on-load in case there is no hash changed, and the last parameter is a time which allows you to "expire" the listener. (I originally implemented this feature for testing purposes. I was trying to avoid having a global variable which would allow for some start/stop method.)

This code could work as a basic building block for any MVC hash based MVC routing mechanism.

Comments: