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.
Put the following:
If the URI is not the document's location this snippet will do what you want.
Most people are aware of the URL properties in document.location. That's great if you're only interested in the current page. But the question was about being able to parse anchors on a page not the page itself.
What most people seem to miss is that those same URL properties are also available to anchor elements:
This is a simple way to test this for the current page URL: