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?
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);
}
if(window.location.hash) {
var hash = window.location.hash.substring(1); //Puts hash in variable, and removes the # character
alert (hash);
// hash found
} else {
// No hash found
}
Here is a simple function that returns true
or false
(has / doesn't have a hashtag):
var urlToCheck = 'http://www.domain.com/#hashtag';
function hasHashtag(url) {
return (url.indexOf("#") != -1) ? true : false;
}
// Condition
if(hasHashtag(urlToCheck)) {
// Do something if has
}
else {
// Do something if doesn't
}
Returns true
in this case.
Based on @jon-skeet's comment.
Partridge and Gareths comments above are great. They deserve a separate answer. Apparently, hash and search properties are available on any html Link object:
<a id="test" href="foo.html?bar#quz">test</a>
<script type="text/javascript">
alert(document.getElementById('test').search); //bar
alert(document.getElementById('test').hash); //quz
</script>
Or
<a href="bar.html?foo" onclick="alert(this.search)">SAY FOO</a>
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 ($('<a href="'+mylink+'">').get(0).search=='bar')) {
// do stuff
}
(but its maybe a bit overdone .. )
Simple:
if(window.location.hash) {
// Fragment exists
} else {
// Fragment doesn't exist
}
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>