Dipak Ojha Dipak Ojha - 29 days ago 5
HTML Question

title is shown only after page refresh

My website has following url. I want to change webpage title when user visits this link http://localhost:8080/krishi/#modal2 (Actually it is popup window). So I've used following code.

if(window.location.hash === "#modal2"){
document.title = "Modal2";
}


I tried using code inside

1. $(document).ready(function(){})
2. window.onload=function(){}


Title is changed in first click and if I refresh url only. I think it is because of cache, So I also add following code to refresh url so it refresh current page once and title is shown.

if(window.location.hash === "#modal2"){
window.location.reload();
document.title = "Modal2";
}


but it not works. It is looped. Please suggest any idea to solve this problem. Thanks in advance.

Answer Source

You should try to use a hashchange event. Here is a demo of firing this event at JSFiddle:

$(window).on('hashchange', function() {
  alert('window.location.hash = ' + window.location.hash);

  if(window.location.hash === "#modal2"){
    document.title = "Modal2";
  }
});