0

Let's say I have this URL in the address bar:

www.example.com/pt.html#myhash

Also I have an anchor that links to

<a id="lang" href="https://www.example.com/en.html">Change Language</a>

What I wanted to archive is to append to that anchor the #myhash tag but only if it's present in the current URL. If not, don't append anything.

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
BornKillaz
  • 592
  • 7
  • 19

1 Answers1

2

Check if window.location.hash is set and that it isn't just a '#' then apply to the anchor

// for demo only set hash
history.pushState(null, null, '#someVal')


const urlHash = location.hash,
     langLink = document.querySelector('#lang');

if (urlHash && urlHash !== '#') {
  langLink.hash = urlHash; 
}

console.log('New href=',langLink.href)
<a id="lang" href="https://www.example.com/en.html">Change Language</a>
charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • But what if the hash tag changes while on the same page? I have several #ids that the user can select on that page. The"lang" link does not get updated. – BornKillaz Apr 09 '21 at 21:28
  • 1
    You can listen to `hashchange` event https://jsfiddle.net/swt94zf1/ – charlietfl Apr 09 '21 at 21:35