HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptCritical

How can you check for a #hash in a URL?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
urlyouhowcheckforhashcan

Problem

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;
}

Solution

Simple use of location hash:

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

Code Snippets

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

Context

Stack Overflow Q#298503, score: 1654

Revisions (0)

No revisions yet.