[Solved-6 Solutions] How can we check for a #hash in a URL using javascript - javascript tutorial



Problem:

How can we check for a #hash in a URL using javascript ?

Solution 1:

URL properties in document.location. Same URL properties are also available to anchor elements:

// To process anchors on click    
jQuery('a').click(function () {
   if (this.hash) {
      // Clicked anchor has a hash
   } else {
      // Clicked anchor does not have a hash
   }
});
// To process anchors without waiting for an event
jQuery('a').each(function () {
   if (this.hash) {
      // Current anchor has a hash
   } else {
      // Current anchor does not have a hash
   }
});

Solution 2:

You can use this:

if(window.location.hash) {
  // Fragment exists
} else {
  // Fragment doesn't exist
}

Solution 3:

Try this:

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
  }

Solution 4:

This is one of the solution:

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

Solution 5:

If the URL is not in the document's location this code will be responsible.

var url = 'example.com/page.html#anchor',
    hash = url.split('#')[1];

if (hash) {
    alert(hash)
} else {
    // do something else
}

Solution 6:

This code helps to solve the problem.

$('#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!
});

Related Searches to How can we check for a #hash in a URL using javascript - javascript tutorial