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?
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 invoke Location
will tell you that it's an illegal constructor. You can still get to things like hash
, query
, protocol
etc by setting your string as the href
property of a DOM anchor element, which will then share all the address properties with window.location
.
Simplest way of doing this is:
var a = document.createElement('a');
a.href = string;
string.hash;
For convenience, I wrote a little library that utilises this to replace the native Location
constructor with one that will take strings and produce window.location
-like objects: Location.js
sometimes you get the full query string such as "#anchorlink?firstname=mark"
this is my script to get the hash value:
var hashId = window.location.hash;
hashId = hashId.match(/#[^?&\/]*/g);
returns -> #anchorlink
$('#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 ;)
var requestedHash = ((window.location.hash.substring(1).split("#",1))+"?").split("?",1);
You can parse urls using modern JS:
var my_url = new URL('http://www.google.sk/foo?boo=123#baz');
my_url.hash; // outputs "#baz"
my_url.pathname; // outputs "/moo"
my_url.protocol; // "http:"
my_url.search; // outputs "?doo=123"
urls with no hash will return empty string.
...or there's a jquery selector:
$('a[href^="#"]')