Search code examples
javascriptback-buttonhashchange

Hash change event in ajax (javascript)


I am actually trying to enable user to bookmark pages and for this, i am using hash change event of javascript. Here is my code:

<script type="text/javascript">
function hashchk()
{
    hashvalue=window.location.hash;
    newhash="";
    for(var i=1;i<hashvalue.length;i++)
    {
        newhash=newhash+hashvalue[i];
    }
    if(hashvalue!="")
    {
        window.location.replace("viewme.php?ppid="+newhash);
    }
}
hashchk();
</script>

Everything here is working except for the fact that, when the user wants to go back to the previous page, he has to press the browser's back button 2 times rather than once.

if he is in http://www.example.com/abc.php#hello on 1st pressing back button, url alone changes to http://www.example.com/abc.php but the page does not load.

But on pressing it the next time, it comes properly. I want them to press it only once. Thanx in advance.


Solution

  • I wasn't entirely clear on your question. It seems like you are trying to fire this if a user comes to a page for the first time with a hash on it (like #html3) so you can refresh their screen with the appropriate data from the server. The question itself doesn't seem directly related to the hashchange event.

    After testing this HTML, I believe it works as you expect. Whenever the page loads and has a #hash on it it will redirect it with it on the query string. This will also work for page refreshes.

    <script>
    function hashchk()
    {
        hashvalue=window.location.hash; 
         if(hashvalue!="") 
         { 
            window.location.replace("viewme.php?ppid="+hashvalue.substring(1)); 
        } 
    }
    hashchk();
    </script>