Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Execute a script when there have been changes to the anchor part of the URL in HTML?
The onhashchange event in HTML executes a script whenever the anchor part (hash fragment) of the URL changes. The anchor part refers to the portion of the URL that comes after the # symbol, commonly used for navigation within a page or single-page applications.
This event is particularly useful for detecting when users navigate using the browser's back/forward buttons or when the URL hash is programmatically modified. The hash change can be detected using either the onhashchange attribute or JavaScript event listeners.
Syntax
Following is the syntax for the onhashchange attribute −
<body onhashchange="scriptFunction()">
Following is the syntax for using addEventListener() method −
window.addEventListener("hashchange", functionName);
Using onhashchange Attribute
The onhashchange attribute can be applied directly to the <body> element. When the hash portion of the URL changes, the specified script function executes automatically.
Example
Following example demonstrates the onhashchange attribute usage −
<!DOCTYPE html>
<html>
<head>
<title>onhashchange Attribute Example</title>
</head>
<body onhashchange="handleHashChange()" style="font-family: Arial, sans-serif; padding: 20px;">
<h2>Hash Change Detection</h2>
<p>Click the button to change the URL anchor part:</p>
<button onclick="changeHash()" style="padding: 10px 15px; margin: 10px;">Change Hash to #welcome</button>
<button onclick="changeHash2()" style="padding: 10px 15px; margin: 10px;">Change Hash to #tutorials</button>
<p id="result" style="margin-top: 20px; font-weight: bold; color: blue;"></p>
<script>
function changeHash() {
location.hash = "welcome";
}
function changeHash2() {
location.hash = "tutorials";
}
function handleHashChange() {
var currentHash = location.hash;
document.getElementById("result").innerHTML = "Hash changed to: " + currentHash;
alert("Hash change detected! New hash: " + currentHash);
}
</script>
</body>
</html>
When you click either button, the URL hash changes and both an alert and text update appear −
Hash Change Detection Click the button to change the URL anchor part: [Change Hash to #welcome] [Change Hash to #tutorials] Hash changed to: #welcome (or #tutorials) (Alert popup: "Hash change detected! New hash: #welcome")
Using addEventListener() Method
The addEventListener() method provides a more flexible approach for handling hash changes. This method allows you to attach multiple event handlers and provides better control over event management.
Example
Following example shows hash change detection using addEventListener() −
<!DOCTYPE html>
<html>
<head>
<title>addEventListener Hash Change Example</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
<h2>Navigation Hash Detection</h2>
<div style="margin: 20px 0;">
<a href="#home" style="margin-right: 15px; text-decoration: none; color: #007bff;">Home</a>
<a href="#about" style="margin-right: 15px; text-decoration: none; color: #007bff;">About</a>
<a href="#contact" style="margin-right: 15px; text-decoration: none; color: #007bff;">Contact</a>
</div>
<button onclick="programmaticChange()" style="padding: 10px 15px; margin: 10px;">Set Hash to #services</button>
<div id="content" style="margin-top: 30px; padding: 15px; border: 2px solid #ddd; border-radius: 5px;">
<p>Click navigation links or the button to see hash changes.</p>
</div>
<script>
function programmaticChange() {
location.hash = "services";
}
// Add event listener for hash changes
window.addEventListener("hashchange", function() {
var newHash = location.hash || "#home";
var content = "";
switch(newHash) {
case "#home":
content = "<h3>Home Section</h3><p>Welcome to the home page!</p>";
break;
case "#about":
content = "<h3>About Section</h3><p>Learn more about us here.</p>";
break;
case "#contact":
content = "<h3>Contact Section</h3><p>Get in touch with us.</p>";
break;
case "#services":
content = "<h3>Services Section</h3><p>Check out our services.</p>";
break;
default:
content = "<p>Hash changed to: " + newHash + "</p>";
}
document.getElementById("content").innerHTML = content;
});
// Load initial content
window.addEventListener("load", function() {
if (!location.hash) {
location.hash = "home";
}
});
</script>
</body>
</html>
This example creates a simple navigation system where clicking links or the button updates the content area based on the hash value −
Navigation Hash Detection [Home] [About] [Contact] [Set Hash to #services] Home Section (or corresponding section based on clicked link) Welcome to the home page!
Practical Use Cases
The onhashchange event is commonly used in the following scenarios −
Single Page Applications (SPAs) − Navigate between different views without page reloads.
Tab Navigation − Switch between tabs while maintaining browser history.
Bookmark Support − Allow users to bookmark specific sections of a page.
Back Button Handling − Respond when users click the browser's back/forward buttons.
Example − Tab Navigation with Hash
Following example demonstrates a tab system using hash changes −
<!DOCTYPE html>
<html>
<head>
<title>Tab Navigation with Hash</title>
<style>
.tabs { display: flex; margin-bottom: 20px; }
.tab { padding: 12px 20px; background: #f0f0f0; margin-right: 5px; cursor: pointer; text-decoration: none; color: #333; }
.tab.active { background: #007bff; color: white; }
.tab-content { padding: 20px; border: 2px solid #ddd; min-height: 100px; }
</style>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
<h2>Tab System with Hash Navigation</h2>
<div class="tabs">
<a href="#tab1" class="tab" id="link-tab1">Profile</a>
<a href="#tab2" class="tab" id="link-tab2">Settings</a>
<a href="#tab3" class="tab" id="link-tab3">Messages</a>
</div>
<div id="tab-content" class="tab-content">
<p>Select a tab to view content.</p>
</div>
<script>
function showTab(tabId) {
// Remove active class from all tabs
var tabs = document.querySelectorAll('.tab');
tabs.forEach(tab => tab.classList.remove('active'));
// Add active class to current tab
document.getElementById('link-' + tabId).classList.add('active');
// Update content
var content = "";
switch(tabId) {
case 'tab1':
content = "<h3>Profile</h3><p>Manage your profile information here.</p>";
break;
case 'tab2':
content = "<h3>Settings</h3><p>Configure your account settings.</p>";
break;
case 'tab3':
content = "<h3>Messages</h3><p>View your messages and notifications.</p>";
break;
}
document.getElementById('tab-content').innerHTML = content;
}
// Handle hash changes
window.addEventListener('hashchange', function() {
var hash = location.hash.substring(1); // Remove # symbol
if (hash) {
showTab(hash);
}
});
// Initialize first tab
window.addEventListener('load', function() {
if (!location.hash) {
location.hash = 'tab1';
} else {
var hash = location.hash.substring(1);
showTab(hash);
}
});
</script>
</body>
</html>
This creates a functional tab system where each tab corresponds to a hash value, and the browser's back/forward buttons work correctly.
Browser Support
The onhashchange event is supported in all modern browsers including Chrome, Firefox, Safari, Edge, and Internet Explorer 8+. It provides reliable hash change detection across different platforms.
Conclusion
The onhashchange event provides an efficient way to detect URL hash changes in HTML. Whether using the attribute directly on the body element or the addEventListener() method, this event enables dynamic content updates and improved navigation in web applications while maintaining browser history functionality.
