Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome not returning hash value

I'm using the following snippet if jQuery JavaScript to return a hash value at the end of a URL. It works perfectly in FF but the alert on line 4 returns empty in Chrome.

Seems like the window.location.hash.substring(1) line does not work. I have also tried window.location.hash.replace("#", "");

// Map Clicks
$("#tab2.tab_content #map").delayed('click', 500, function() {
    state = window.location.hash.substring(1);
    alert(state);
    jsonLink = 'http://ml.uscm.org/ministries.json?state=' + state + '&active=true&callback=?';
    getMapResults();
    return false;
});

What's the trick to retrieving a hash value from the URL in Chrome?

The URL is built like this :

http://www.ourdomain.com/thispage.html#IL

Where IL is a two letter abbreviation for a state. I want to get the "IL".

I have a working demo here:

http://richcoy.com/locator/index2.html

Click on the Search by State tab in Chrome then click on a state and you'll see the issue. The browser shows that the url that it wants to go to is built correctly. –

Thanks.

like image 899
Rich Coy Avatar asked Oct 10 '13 14:10

Rich Coy


1 Answers

You may want to try this instead:

$(window).on('hashchange', function() {
    console.log(window.location.hash.substring(1));
});

The click event triggers before the hashchange event so you can't rely on your map click implement (even if you delayed it).

Supported browsers list for hashchange: http://caniuse.com/hashchange

In case you don't have to use hash, here is a simpler solution:

$("#tab2.tab_content #map a").click(function() {
    console.log($(this).attr('href').substring(1));
});

In summary, you shouldn't use any kind of delayed methods.

like image 59
anvoz Avatar answered Oct 22 '22 11:10

anvoz