We can detect the changes in URL hash value using JavaScript events. The fragment identifier in a URL that starts with the "#" symbol is known as the hash value.
JavaScript fires the hashchange
and popstate
events whenever the hash value in a URL changes. We can listen to these events to identify the changes in the URL hash in JavaScript.
When users add or change the URL hash in JavaScript without reloading the page, you can use any of these events to perform some functionalities.
Let's see how can we listen to these events.
Detect URL Hash Change With JavaScript hashchange event
You have to call the addEventListener()
method on the window
object. We can attach the hashchange
event with this method.
window.addEventListener("hashchange", () => {
console.log("The hash value has changed");
});
If the current URL is https://example.com/post#comments
in your browser, we can change the "#comments" to anything else like "#reviews" in the URL.
Whenever the value changes, the hashchange
event will fire, and the callback function will execute.
You can get the hash value from the URL inside this callback function using the location
object in Javascript.
Detect URL Hash Change With JavaScript popstate event
You can also use the popstate
event using the addEventListener()
method in JavaScript. This event gets fired when the hash value changes in the current URL.
window.addEventListener("popstate", () => {
console.log("The hash value has changed");
});
You will call the addEventListerner()
method on the window
object and put popstate
as the event name.
The callback function will be executed whenever the hash value changes in the URL. If you add a new value to the URL for the first time, JavaScript will also fire the event.
Also Read: How to Check For Hash (#) Value in a URL Using JavaScript
Conclusion
These are the 2 events in JavaScript that we can use to identify the changes in URL hash. It doesn't matter which event you use in your project, you will get the same result.
You have to call the addEventListener()
method on the window
object. Then pass hashchange
or popstate
as the event name.
JavaScript will track the changes in hash value and execute the code from the callback function. This is how you can detect URL hash change in JavaScript.