Search code examples
jqueryfragment-identifier

How to replace Hash in Link


I want to add the hash of the url to the href attribute of a navigation:

<ul>
  <li><a href="/bla">Bla</a></li>
  <li><a href="/bli">Bli</a></li>
  <li ><a href="/blu">Blu</a></li>
</ul>

I have this code:

  $(window).on('hashchange', function (e) {
      console.log(location.hash);
      $("a").attr('href', function(_, href){
        return href + window.location.hash
      });
  });
  if (window.location.hash) {
      $(window).trigger('hashchange')
  }

Now when I click on a submenu or enter the url by hand with the hash the menu gets updated like this:

<ul>
  <li><a href="/bla#hashVlaue">Bla</a></li>
  <li><a href="/bli#hashVlaue">Bli</a></li>
  <li ><a href="/blu#hashVlaue">Blu</a></li>
</ul>

This is working. But now if I click on the submenu again the hash is appended and not replaced. Since the page is not reloaded when clicking on the submenu the links start to look like this:

<a href="/blu#hashOne#hashTwo#Three#Four">Blu</a>

I just want one hash and if there is already one it should get replaced. How do I do this?


Solution

  • You are always appending to href in your code. Check the line href + window.location.hash in hashchange callback. That's why it is always appending to the previous value. What you need is

    return href.split("#")[0] + window.location.hash
    

    Cheers :)