Home > front end >  Change meta title based on url #id
Change meta title based on url #id

Time:11-19

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.

CodePudding user response:

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>
  • Related