Detect Change in Hash Value of URL with JavaScript

12/23/2021

Contents

In this article, you will learn how to detect change in hash value of URL with JavaScript.

Detect change in hash value of URL

If you want to detect a change in the hash (#) value of the URL, use windonw’s hashchange event.
The hashchange is an event that fires when the hash of the URL has changed and be used within the addEventListener method.

The syntax is as follows.

window.addEventListener('hashchange', function, false);

By specifying a function in the second argument, it is possible to execute the processing when the hash value of the URL has changed.

Change the URL hash and execute the process

Here’s a simple sample script.
Set in-page links in the a tags so that clicking it updates the hash value of the URL.
In JavaScript, an alert is displayed when the hash value of the URL has changed, and the hash is output after the change.

HTML

<a href="#test1">test1</a>
<a href="#test2">test2</a>
<a href="#test3">test3</a>
<a href="#test4">test4</a>
<a href="#test5">test5</a>

JavaScript

 const myFunc = ()=>{
    alert('Hash value:' + location.hash);
}

window.addEventListener('hashchange', myFunc, false);