user835059
user835059

Reputation: 163

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 in the link I receive the previous var.

Example:

If my first Click is 11111 I receive message Empty and if my second click is 222222 I receive a=1&aa=10

Upvotes: 3

Views: 4049

Answers (2)

Royi Namir
Royi Namir

Reputation: 148524

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");  }
    }
}); 

Upvotes: 5

Rory McCrossan
Rory McCrossan

Reputation: 337560

This is because the click event is fired before the hash fragment is appended 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 the variables on page load, then you would need to read it from the URL using location.hash.

Example fiddle

Upvotes: 2

Related Questions