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
Selected Reading
What is the usage of onhashchange event in JavaScript?
The onhashchange event occurs when the anchor part (hash) of the URL changes. This event is useful for creating single-page applications where different URL fragments represent different views or states.
Syntax
window.onhashchange = function() {
// Code to execute when hash changes
};
// Or using addEventListener
window.addEventListener('hashchange', function() {
// Code to execute when hash changes
});
Example: Basic Hash Change Detection
<!DOCTYPE html>
<html>
<body>
<button onclick="changeHash()">Change to #about</button>
<button onclick="changeHash2()">Change to #contact</button>
<p id="output">Current hash: <span id="currentHash">(none)</span></p>
<script>
// Function to handle hash changes
function handleHashChange() {
var hash = location.hash || '(none)';
document.getElementById('currentHash').textContent = hash;
alert('Hash changed to: ' + hash);
}
// Attach event listener
window.onhashchange = handleHashChange;
// Functions to change hash
function changeHash() {
location.hash = 'about';
}
function changeHash2() {
location.hash = 'contact';
}
// Display initial hash
handleHashChange();
</script>
</body>
</html>
Example: Using addEventListener Method
<!DOCTYPE html>
<html>
<body>
<a href="#home">Home</a> |
<a href="#products">Products</a> |
<a href="#services">Services</a>
<div id="content">Click a link above</div>
<script>
window.addEventListener('hashchange', function() {
var hash = location.hash.substring(1); // Remove # symbol
var content = document.getElementById('content');
switch(hash) {
case 'home':
content.innerHTML = '<h2>Home Page</h2><p>Welcome to our website!</p>';
break;
case 'products':
content.innerHTML = '<h2>Products</h2><p>Our amazing products...</p>';
break;
case 'services':
content.innerHTML = '<h2>Services</h2><p>Professional services...</p>';
break;
default:
content.innerHTML = '<p>Page not found</p>';
}
});
</script>
</body>
</html>
Key Points
- The event fires when the URL hash (fragment identifier) changes
- Access the current hash using
location.hash - Use
window.onhashchangeoraddEventListener('hashchange') - The hash includes the # symbol, use
substring(1)to remove it - Useful for single-page applications and navigation without page reloads
Browser Compatibility
The onhashchange event is supported in all modern browsers including Internet Explorer 8+, Chrome, Firefox, Safari, and Edge.
Conclusion
The onhashchange event enables dynamic content updates based on URL hash changes. It's essential for creating smooth single-page application navigation without full page reloads.
Advertisements
