Updating URL hash without page reload

12,722

Solution 1

Not exactly cross browser, but you can get cross browser hashchange workarounds if you want,

<script>
$(window).on('hashchange load',function(){
    var id = parseInt(window.location.hash.replace("#", ""));
    alert(id);
});
</script>

<!-- START URL: test.htm#1 -->
<a href='#1'>#1</a>
<a href='#2'>#2</a>
<a href='#3'>#3</a>

using bind: http://jsfiddle.net/KdqWK/1/

using on: http://jsfiddle.net/KdqWK/2/

Solution 2

I would use the onpopstate and onhashchange event listeners:

<html>
<head>
<title>Untitled Document</title>
<script type="text/javascript">

    if (typeof window.onpopstate != 'undefined') {
        window.onpopstate = curHash;
    } else if (typeof window.onhashchange != 'undefined') {
        window.onhashchange = curHash;
    }

    function curHash() {
        var h = window.location.hash;
        if (h == '') return; // no hash. this is probably the first load
        h = h.substr(1); // hash always starts with #
        alert('hash: ' + h);
    }

</script>
</head>

<body>
<ul style="margin:0; padding:0;">
    <li><a href="#1">Click here for 1</a></li>
    <li><a href="#2">Click here for 2</a></li>
    <li><a href="#3">Click here for 3</a></li>
    <li><a href="#4">Click here for 4</a></li>
</ul>
</body>
</html>

Solution 3

Instead of calling curHash in onclick, call it in href after setting hash.. please find the following code..

<a href='javascript:location.hash="#1";CurHash();'>#1</a>
<a href='javascript:location.hash="#2";CurHash();'>#2</a>
<a href='javascript:location.hash="#3";CurHash();'>#3</a>
Share:
12,722
DaneSoul
Author by

DaneSoul

Web-developer: PHP, MySQL, HTML, CSS, JavaScript, JQuery (english &amp; russian speaking)

Updated on June 30, 2022

Comments

  • DaneSoul
    DaneSoul almost 2 years
    <script>
    function CurHash(){
        var id = parseInt(window.location.hash.replace("#", ""));
        alert(id);
    }
    </script>
    
    <!-- START URL: test.htm#1 -->
    <a href='#1' onClick='CurHash()'>#1</a>
    <a href='#2' onClick='CurHash()'>#2</a>
    <a href='#3' onClick='CurHash()'>#3</a>
    

    If we are now on test.htm#1 and click link #2, alert shows 1 number, not 2, and after this hash in URL is changed to 2. When you next click 3, it will show prevouse 2, and so on.

    There is the problem for me, because I use hash for scrolling my page content on fixed height (can't use anchors due to architecture issues), and with such behavour after clicking link scroll will happened only on second click, what is completely wrong.

    QUESTION: How can I update hash and take updated (not previouse) value for further use, without reloading page in browser (all content for scrolling already on page, reload it from server isn't good solution).