views:

71

answers:

3

Say I have an anchor on a webpage like so:

<a name="comegetit"></a>

Is there a way of running a javascript if the page is arrived at by a link that lands on this anchor? (e.g. a link like <a href="http://myawesomewebpage.com/page#comegetit"&gt;&lt;/a&gt;). I don't think there is but I would like there to be.

+1  A: 

You can try to act on the onload event and check for the window.location content to extract the fragment identifier... it should work.

Stefano Borini
+3  A: 

If you only expect this one string as the URL anchor:

if(window.location.hash == '#comegetit'){
  // Do your stuff.
}

If you're doing anything else complex, you can also match window.location.hash against a regular expression.

Ron DeVera
The hash value returns with #. (ie "#comegetit")
enduro
That did the trick. Thanks.
brad
Thanks, enduro -- slipped my mind. Updated.
Ron DeVera
+2  A: 

I use Really Simple History (http://code.google.com/p/reallysimplehistory/)

Then, in my code I do something like this:

window.dhtmlHistory.create();
window.dhtmlHistory.initialize();   
window.dhtmlHistory.addListener(function(hash){
    // this is where you process your hash and do something special
    // and totally funky
});

This even gets fired on the initial page load, if you happen to bookmark a hash tag or whatnot.

Quite useful, and abstracts away all the browser specific B.S. that comes with window.location.hash

Josh

Josh
Thanks. I'll go with the simple window.location.hash solution for now and see if I run into problems. I don't feel like learning another library today.
brad