Skip to content
Advertisement

Change meta title based on url #id

I have a static html website. Our server does not support php/c# etc…

Can JS / JQuery / Ajax or others do the following:

If the url is:

Https://example.com/page , the meta title will be e.g. “home page”.

Https://example.com/example#1 , the meta title will be to “new meta title”

Https://example.com/example#29 , the meta title will be e.g. “a different title”

Effectively , can the meta title be dynamic and displays different text based on what the url #identifier is.

Advertisement

Answer

Something like this should do it:

<script>
  function setTitleBasedOnUrlHash() {
    var hash = window.location.hash;
    if (hash === '#1') {
      document.title = 'new meta title';
    } else if (hash === '#2') {
      document.title = 'a different title';
    }
    // ...more else ifs here...
  }

  window.onload = setTitleBasedOnUrlHash;
</script>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement