Home >Web Front-end >JS Tutorial >How Can JavaScript Detect Hash Anchor Links in URLs?

How Can JavaScript Detect Hash Anchor Links in URLs?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-15 09:43:09702browse

How Can JavaScript Detect Hash Anchor Links in URLs?

How to Identify Hash Anchor Links in URLs with JavaScript

Whether you're building dynamic web pages or developing interactive widgets, it's often necessary to distinguish URLs with hash anchor links from those without. To accomplish this in JavaScript, you can leverage the location.hash property.

Check for Hash Anchor Links

To determine if a URL contains a hash anchor link, you can utilize the following code snippet:

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

The location.hash property returns the portion of a URL that follows the hash symbol (#), including the hash symbol itself. When a hash anchor link is present in the URL, location.hash will be a non-empty string. In the absence of a hash anchor link, location.hash will be an empty string.

Example Usage

Suppose you have the following HTML code:

<a href="page.html#anchor">Go to Anchor</a>

If a user clicks on this link, the browser will navigate to the URL "page.html#anchor". Using the JavaScript code provided above, you can check whether a hash anchor link is present in the URL as follows:

if (window.location.hash === "#anchor") {
  // Code to execute when the anchor exists
}

By utilizing the location.hash property, you can easily determine the presence of hash anchor links in URLs, enabling you to implement conditional logic accordingly.

The above is the detailed content of How Can JavaScript Detect Hash Anchor Links in URLs?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn