javascriptjqueryhashwindow.locationhashchange

Current URL hashchange event append new hash to target URL and link out to it


I have a page ex: test123.com/go#1 on that page if the hash changes ex: test123.com/go#2 I'd like to append the new hash value to a target URL and link out to it: test123.com/gopage2#2

Here's the code I've tried so far:

var url = window.location.href;
var res = url.split("#");
var hash = "#" + res[1];
$(window).on('hashchange', function() {
  window.location = 'test123.com/gopage2' + hash;
});

When the hash changes nothing happens... Any ideas?


Solution

  • Assuming you meant to update url, res, and hash in the event handler, and use the hash in the new URL, try this:

    $(window).on('hashchange', function() {
      var url = window.location.href;
      var res = url.split("#");
      var hash = "#" + res[1];
      window.location = 'test123.com/gopage' + res[1] + hash;
    });