Organizational Research By

Surprising Reserch Topic

Experts Most Trusted Topic


How can you check for a #hash in a URL using JavaScript?


I have some jQuery JavaScript code that I want to run only when there is a hash (#) anchor link in a URL. How can you check for this character using JavaScript? I need a simple catch-all test that would detect URLs like these:

  • example.com/page.html#anchor
  • example.com/page.html#anotheranchor

Basically something along the lines of:

if (thereIsAHashInTheUrl) {        
    do this;
} else {
    do this;
}

If anyone could point me in the right direction, that would be much appreciated.


asked May 20, 2015 in JAVASCRIPT by rahulgii
0 votes
78 views



Related Hot Questions



Government Jobs Opening

answered May 20, 2015 by rahulgii
0 votes

Put the following:

 type="text/javascript">
    if (location.href.indexOf("#") != -1) {
        // Your code in here accessing the string like this
        // location.href.substr(location.href.indexOf("#"))
    }
answered May 20, 2015 by rahulgii
0 votes

f the URI is not the document's location this snippet will do what you want.

var url = 'example.com/page.html#anchor',
    hash = url.split('#')[1];

if (hash) {
    alert(hash)
} else {
    // do something else
}
answered May 20, 2015 by rahulgii
0 votes
$('#myanchor').click(function(){
    window.location.hash = "myanchor"; //set hash
    return false; //disables browser anchor jump behavior
});
$(window).bind('hashchange', function () { //detect hash change
    var hash = window.location.hash.slice(1); //hash to string (= "myanchor")
    //do sth here, hell yeah!
});

This will solve the problem ;)

answered May 20, 2015 by rahulgii
0 votes

Here's what you can do to periodically check for a change of hash, and then call a function to process the hash value.

var hash = false; 
checkHash();

function checkHash(){ 
    if(window.location.hash != hash) { 
        hash = window.location.hash; 
        processHash(hash); 
    } t=setTimeout("checkHash()",400); 
}

function processHash(hash){
    alert(hash);
}
answered May 20, 2015 by rahulgii
0 votes

Partridge and Gareths comments above are great. They deserve a separate answer. Apparently, hash and search properties are available on any html Link object:

 id="test" href="foo.html?bar#quz">test
 type="text/javascript">
   alert(document.getElementById('test').search); //bar
   alert(document.getElementById('test').hash); //quz

Or

 href="bar.html?foo" onclick="alert(this.search)">SAY FOO

Should you need this on a regular string variable and happen to have jQuery around, this should work:

var mylink = "foo.html?bar#quz";

if ($('+mylink+'">').get(0).search=='bar')) {
    // do stuff
}

(but its maybe a bit overdone .. )

answered May 20, 2015 by rahulgii

...