views:

9287

answers:

4

Hi,

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.

+23  A: 

Simple:

if(window.location.hash) {
  // Fragment exists
} else {
  // Fragment doesn't exist
}
Gareth
Additional: the .location object is only available on the current window's URL, you can't do this for an arbitrary URL (e.g. one stored in a string variable)
Gareth
Also, location properties like .hash and .query are also available on <a> elements
Gareth
+1  A: 

Have you tried this?

if (url.indexOf("#") != -1)
{
}

(Where url is the URL you want to check, obviously.)

Jon Skeet
+5  A: 

Hi buddy: put the following:

<script type="text/javascript">
    if (location.href.indexOf("#") != -1) {
        // Your code in here accessing the string like this
        // location.href.substr(location.href.indexOf("#"))
    }
</script>

Good luck!

José Leal
+2  A: 

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