Search code examples
javascriptjqueryhashchange

JavaScript: calling a function by name on hashchange


I'm trying to call a function given the function name in the hash string. I have the following code:

$(window).on('hashchange', function() {
  //alert(location.hash.substring(1, location.hash.length));
  window[location.hash.substring(1, location.hash.length)];
});

function test() {
  alert('123!');
}

The funny thing is, when I uncomment the alert call, everything works as expected. When the alert is commented, however, it doesn't work.

Any ideas?


Solution

  • window[location.hash.substring(1, location.hash.length)];
    

    doesn't call a function.

    If you want to call the function whose name is location.hash.substring(1, location.hash.length), you may do

    window[location.hash.substring(1, location.hash.length)]();
    

    Side note :

    location.hash.substring(1, location.hash.length)
    

    can be shortened in

    location.hash.slice(1)