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.
...or there's a jquery selector:
Here's what you can do to periodically check for a change of hash, and then call a function to process the hash value.
Throwing this in here as a method for abstracting location properties from arbitrary URI-like strings. Although
window.location instanceof Location
is true, any attempt to invokeLocation
will tell you that it's an illegal constructor. You can still get to things likehash
,query
,protocol
etc by setting your string as thehref
property of a DOM anchor element, which will then share all the address properties withwindow.location
.Simplest way of doing this is:
For convenience, I wrote a little library that utilises this to replace the native
Location
constructor with one that will take strings and producewindow.location
-like objects: Location.jsUsually clicks go first than location changes, so after a click is a good idea to setTimeOut to get updated window.location.hash
or you can listen location with:
I wrote a jQuery plugin that does something like what you want to do.
It's a simple anchor router.
This will solve the problem ;)