user6098620
user6098620

Reputation:

Updating Page Title Based on URL

Let's say the <title> of example.com is example

How to automatically update the page title for example.com/#city1 to example city1 and example.com/#city2 to example city2 and so on.

I have only an index.html file and I don't want to add php file to my html file so please help me with a simple and clean code.

Upvotes: 1

Views: 900

Answers (2)

Ankit Singh
Ankit Singh

Reputation: 1477

You have to use atleast javascript.

Try this:

var str = 'example.com/#city1';
var str1 = str.substring(0,str.indexOf('.'))+' '+str.substring((0,str.indexOf('#')+1));
document.getElementsByTagName('p')[0].innerHTML = str1;
//in your case replace p with title tag
<p>Change Me</p>

Upvotes: 0

Claudio
Claudio

Reputation: 5203

If you want a dynamic solution, that will update the page title everytime the anchor/hash changes:

$(function(){
  // event
  $(window).on('hashchange', function() {
    let hash = location.hash.replace( /^#/, '' );
    document.title = 'example ' + hash;
  });

  // just to set on page load (you might need to tweak in case there is no hash)
  $(window).trigger('hashchange');
});

Upvotes: 1

Related Questions