GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Home
  • ES6
  • Web
  • JS BOM
  • JS DOM
  • Web API
  • React
  • Node.js
  • Express
  • React Native
  • JavaScript Array Methods
  • JavaScript String Methods
  • Regular Expressions
  • ES Next

This view

  • Original page
  • New address

GeezerVison is showing www.javascripttutorial.net — JavaScript hashchange Event

Home » JavaScript DOM » JavaScript hashchange Event

Summary: in this tutorial, you will learn about the JavaScript hashchange event and how to handle it effectively.

Introduction to the JavaScript hashchange event #

The URL hash is everything that follows the pound sign (#) in the URL. For example, suppose that you have the following URL:

https://www.javascripttutorial.net/javascript-dom/javascript-hashchange/#header

In this URL, the hash is header.

When the hash changes to footer, the hashchange event will fire:

https://www.javascripttutorial.net/javascript-dom/javascript-hashchange/#footer

In this example, the hash changes from #header to #footer.

To attach an event listener to the hashchange event, you call the addEventListener() method on the window object:

window.addEventListener('hashchange',() =>{
    console.log('The URL has has changed');
});

To get the current URL hash, you access the hash property of the location object:

window.addEventListener('hashchange',() => {
    console.log(`The current URL hash is ${location.hash}`);
});

Additionally, you can handle the hashchange event by assigning an event listener to the onhashchange property of the window object:

window.onhashchange = () => {
    // handle hashchange event here
};

JavaScript hashchange event example #

The hashchange event can be useful for creating a single-page application (SPA) or updating content dynamically without reloading the whole page.

The following example shows how to use the hashchange event to update the content of a div based on the URL hash.

First, create a simple HTML file (index.html) with some navigation links and a main section:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>JavaScript HashChange Example</title>
        <link rel="stylesheet" href="css/style.css">
        <script src="js/app.js" defer></script>
    </head>
    <body>
        <header>
            <nav>
                <a href="#home">Home</a>
                <a href="#about">About</a>
                <a href="#contact">Contact</a>
            </nav>
        </header>
        <main id="content">
            <h1>HashChange Event Demo!</h1>
            <p>Click the links above to change the content.</p>
        </main>
    </body>
</html>

Second, crate a JavaScript file app.js that handles the hashchange event and updates the content respectively:

const updateContent = () => {
  const content = document.getElementById('content');
  const hash = window.location.hash.substring(1); // Remove the '#' from the hash

  switch (hash) {
    case 'home':
      content.innerHTML = `
          <h1>Home</h1>
          <p>Welcome to the home page.</p>
        `;
      break;
    case 'about':
      content.innerHTML = `
          <h1>About</h1>
          <p>Learn more about us on this page.</p>
        `;
      break;
    case 'contact':
      content.innerHTML = `
          <h1>Contact</h1>
          <p>Get in touch with us.</p>
        `;
      break;
  }
};

// Event listener for hashchange
window.addEventListener('hashchange', updateContent);

Output:

Summary #

  • The hashchange event fires when the URL hash changes.
  • To register an event handler, you call the addEventListener() method or assign an event handler to the onhashchange property of the window object.

Was this helpful?

Thank you for your feedback!

You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.