Search code examples
javascripthtmlajaxhashchange

I need to update my page using Anchor (#) in URL


index.php

<html>
 <head>
  <title>My Title</title>
  <script type="text/javascript">
   function getLink(data) {
    document.getElementById("box").innerHTML="This is "+data;
   }
  </script>
 </head>
 <body>
  <a href="#home" onClick="getLink('Home')">Home</a><br />
  <a href="#profile" onClick="getLink('Profile')">Profile</a><br />
  <a href="#message" onClick="getLink('Message')">Message</a><br />
  <a href="#setting" onClick="getLink('Setting')">Setting</a><br />
  <hr />
  <div id="box"></div>
 </body>
</html>

Output

Home
Profile
Message
Setting


This is Home

As the code says my Div contents updated when i click any of the link but the problem is that when user goes back by clicking Back Button of Browser the content of my Div donot changes.
I want that either user Goes Back, Goes Forward or he directly puts the path in the address bar www.*****/index.php#profile the content of my Div should be change.

Note
I used document.location.hash to get the value of hash like this :

<head>
 <script>
  var hashValue=document.location.hash;
  alert(hashValue);
 </script>
</head>

but it works only when user goes back and then refresh the page

Plz help me how can i achieve this :(


Solution

  • You need to use hashchange event:

    function hash_changed() {
        var data = document.location.hash.substr(1);
        var box = document.getElementById("box");
    
        if (data) {
            // inner page
            box.innerHTML="This is " + data;
        }
        else {
            // homepage
            box.innerHTML = "";
        }
    }
    
    window.onhashchange = function () {
        hash_changed();
    };
    
    window.onload = function () {
        hash_changed();
    };
    

    Also when you are using hashchange event, there is no need to set onclick for your links:

    <a href="#home">Home</a>
    <a href="#profile">Profile</a>
    <a href="#message">Message</a>
    <a href="#setting">Setting</a>
    

    When user click on a link, the hash automatically changes (with href attribute of link), and hashchange event get fired.

    Check DEMO here.


    First Time

    When a user come to your page for the first time with a hash:

    http://fiddle.jshell.net/B8C8s/9/show/#message
    

    We must show the wanted page (message here), so we must run hash_changed() function we declare above, at first time. For this, we must wait for DOM ready or window.onload.