JavaScript hashchange Event newURL Property: The New URL After Hash Change

The JavaScript hashchange event is triggered when the fragment identifier (the part of the URL after the # symbol, also known as the hash) of the document’s URL changes. The newURL property of the hashchange event provides the new, updated URL after the hash change has occurred. This property is crucial for understanding the new state of the page’s URL, particularly in single-page applications (SPAs) where routing is often handled via URL hashes.

Understanding the hashchange Event

The hashchange event allows you to monitor changes to the URL’s hash portion without causing a full page reload. This is especially useful in SPAs where different views are loaded dynamically based on the URL hash. For instance, a website may use #home, #about, or #contact to navigate between different sections without reloading.

The newURL Property

The newURL property is a read-only property that returns the entire new URL, including the updated hash. This property helps in determining the new location of the page after a hash change has taken place.

Syntax

The newURL property can be accessed through the hashchange event object:

window.addEventListener("hashchange", function(event) {
  const newURL = event.newURL;
  // Your logic using the new URL
});

Key Attributes

Attribute Type Description
`newURL` String A read-only property that contains the new URL of the document after the hash has changed.

Examples

Let’s delve into some practical examples to see how you can utilize the newURL property effectively.

Basic Example: Displaying the New URL

In this example, we’ll listen for the hashchange event and display the new URL in a designated HTML element.

<p>Click links below to change the hash:</p>
<a href="#section1">Section 1</a> | <a href="#section2">Section 2</a> |
<a href="#section3">Section 3</a>
<p id="newUrlDisplay1"></p>

<script>
  window.addEventListener('hashchange', function(event) {
    const newUrlDisplayElement1 = document.getElementById('newUrlDisplay1');
    newUrlDisplayElement1.textContent = 'New URL: ' + event.newURL;
  });
</script>

Here, every time the URL hash changes (by clicking one of the links), the event handler fetches the newURL property and sets the text content of the p element with id="newUrlDisplay1" to show the updated URL.

Output:

Initially, the paragraph below the links is empty. When you click on the link “Section 1”, it will output:

New URL: [current URL]#section1

Similarly, when you click on “Section 2”, the output will be:

New URL: [current URL]#section2

Example: Extracting Hash Fragment

In this example, instead of showing the entire new URL, we will extract only the hash portion, demonstrating a practical use case.

<p>Click links below to change the hash:</p>
<a href="#page1">Page 1</a> | <a href="#page2">Page 2</a> |
<a href="#page3">Page 3</a>
<p id="hashFragmentDisplay1"></p>

<script>
  window.addEventListener('hashchange', function(event) {
    const hashFragmentDisplayElement1 = document.getElementById('hashFragmentDisplay1');
    const newHash1 = new URL(event.newURL).hash;
    hashFragmentDisplayElement1.textContent = 'New Hash: ' + newHash1;
  });
</script>

In this example, we extract only the hash portion by creating a new URL object from event.newURL using new URL(event.newURL) and access the hash property.

Output:

Initially, the paragraph below the links is empty. When you click on the link “Page 1”, it will output:

New Hash: #page1

Similarly, when you click on “Page 2”, the output will be:

New Hash: #page2

Example: Implementing Basic SPA Navigation

This advanced example simulates basic single-page application navigation by using the newURL to display different content based on the hash fragment.

<nav>
  <a href="#home">Home</a> | <a href="#products">Products</a> |
  <a href="#contact">Contact</a>
</nav>

<div id="contentArea1">
  <p>Welcome to the Home Page!</p>
</div>
<script>
  const contentArea1 = document.getElementById('contentArea1');
  function loadContent1(hash) {
    switch (hash) {
      case '#home':
        contentArea1.innerHTML = '<p>Welcome to the Home Page!</p>';
        break;
      case '#products':
        contentArea1.innerHTML = '<p>Explore our amazing products!</p>';
        break;
      case '#contact':
        contentArea1.innerHTML = '<p>Get in touch with us!</p>';
        break;
      default:
        contentArea1.innerHTML = '<p>Page not found.</p>';
    }
  }

  window.addEventListener('hashchange', function(event) {
    const newHash2 = new URL(event.newURL).hash;
    loadContent1(newHash2);
  });

  // Load initial content
  loadContent1(window.location.hash);
</script>

This example demonstrates how to use the new URL to dynamically load different content into the contentArea1 div, simulating SPA navigation. A loadContent function is used to decide which content to load based on the hash fragment.

Output:

Initially, when the page loads (without any hash in the URL), the output will be:

Welcome to the Home Page!

When you click on “Products”, the output will be:

Explore our amazing products!

When you click on “Contact”, the output will be:

Get in touch with us!

Browser Support

The hashchange event and its newURL property are widely supported across modern web browsers, ensuring compatibility for your web applications. 🚀

Browser Version Support
Chrome 1+ ✅ Full Support
Firefox 3.6+ ✅ Full Support
Safari 5+ ✅ Full Support
Edge 12+ ✅ Full Support
Opera 10.6+ ✅ Full Support
Internet Explorer 8+ ✅ Full Support

Tips and Best Practices

  • Use URL Object: It’s good practice to use the URL object (e.g., new URL(event.newURL).hash) to easily manipulate the URL and extract the hash fragment.
  • Initial Load: Remember to handle the initial load scenario by calling your hash-handling function with window.location.hash when the page first loads to ensure the content matches the URL hash.
  • Error Handling: If the URL is not well-formed or if there’s an issue with parsing, handle potential errors gracefully within your event handler.
  • Accessibility: While using hash-based navigation, keep accessibility in mind. Ensure that changes to content are announced using ARIA attributes, especially if you’re creating complex single-page applications.

Conclusion

The hashchange event and its newURL property are essential for handling URL hash changes in JavaScript, particularly for single-page applications. By leveraging the newURL property effectively, you can build dynamic, navigable, and responsive web applications. Understanding these concepts and applying the examples above will significantly improve your ability to manage navigation and state within your web projects. 🎊