Dynamic Hash-Based Title Handling in JavaScript

Explore our JavaScript category, where you’ll find loads of helpful articles and tutorials for everyone, whether you’re just starting out or a pro developer. Learn about different JavaScript functions that can be used in various projects according to their specific requirements.
this function handleHashChange that is triggered when the hash in the URL changes. The function gets the updated hash value and logs it to the console. Additionally, it adds the hash as a class to the body element if there is a hash value.
function handleHashChange() {
// Get the updated hash value
var hash = window.location.hash.substring(1);
console.log(“Hash changed: ” + hash);
// Your code logic based on the hash change goes here
if (hash) {
document.body.classList.add(hash);
}
}
// Attach the event listener to the hashchange event
window.addEventListener(“hashchange”, handleHashChange);
This code is commonly used in single-page applications (SPAs) or websites that use hash-based navigation to update the content dynamically without a full page reload. Adding the hash as a class to the body element allows you to apply styles or execute specific logic based on the current hash value.