home projects speaker

Javascript Hash onChange event

Note

Please note that this is an archived post, so links, code and the communicated message might be outdated. YMMV

A pretty nifty solution to bind an event (err) to the window.location.hash string.

javascript
var onHashChange = function(event) {
  //get hash function
  var getHashValue = function() {
    var arr = window.location.hash.split('#');
   var hasValue = arr[1];
   //sets default
   if (typeof hasValue == 'undefined') {
      return false;
    }

   var hashLen = hasValue.indexOf('?');
   if(hashLen>0){
     hasValue = hasValue.substring(0,hashLen);
    }
    return hasValue;
 }

 //last hash
  var lastHash = getHashValue();

  //checker
  (function watchHash() {
    var hash = getHashValue();

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

   var t = setTimeout(watchHash, 100);

 })();
}

onHashChange(function() {
  // your code here
};

AND YES, this is supported in all the latest browsers!


About the author

Hi! My name is Alexander, and I am a creative frontender, specializing in UX, accessibility, universal design, frontend-architecture, node and design systems. I am passionate with open source projects and love to dabble with new emerging technologies related to frontend. With over 26 years of frontend experience, I have earned the right to be called a veteran. I am a lover of life, technologist at heart. If I am not coding, I am cooking and I love whisky and cigars. Oh, and coffee, I LOVE coffee!

If you want to know more about me, here is some links you might want to check out: GitHub, Instagram, Twitter, LinkedIn, CodePen, Slides.com, npm,

Speaker

I am also an avid speaker on several topics! Check out some of the things I speak about, and contact me if you are interested in having me at your next event!