JQuery Hash Navigation

I have a simple javascript function to get hash variables:

$(document).ready(function(){
    $("a").click(function(){
        nav_anchor()
    });
    function nav_anchor() {
        var aurl = location.hash;
        aurl = aurl.split('#');
        if (aurl[1]) { alert(aurl[1]); }
        else { alert("Empty");  }
    }
}); 
<a href="#a=1&aa=10">11111111111</a>
<a href="#b=1&bb=10">22222222222222</a>
<a href="#c=1&cc=10">333333333</a>

But if I click on the link, I get the previous var.

Example:

If my first click 11111, I get a message Empty, and if my second click 222222, I geta=1&aa=10

+3
source share
2 answers

http://jsbin.com/uxitoy/2/edit

$(document).ready(function(){
    $("a").click(function(){
        nav_anchor(this);
    });
    function nav_anchor(o) {
        var aurl = o.hash;
        aurl = aurl.split('#');
        if (aurl[1].length>0) { alert(aurl[1]); }
        else { alert("Empty");  }
    }
}); 
+5
source

This is because the click event is fired before the hash fragment is added to the URL. Instead of getting the hash from the URL, get it from the link:

$("a").click(function(){
    nav_anchor(this)
});

function nav_anchor(el) {
    var aurl = el.href;
    aurl = aurl.split('#');
    if (aurl[1]) { alert(aurl[1]); }
    else { alert("Empty");  }
}

If you want to get variables when the page loads, you will need to read it from the URL using location.hash.

Script example

+2
source

All Articles