Automatically Apply Classes to Body Element Based on URL Hash 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.
A JavaScript code snippet that uses the DOMContentLoaded event to add a class to the body element based on the current hash state in the URL.
document.addEventListener(‘DOMContentLoaded’, function() {
// Get the current hash state from the URL
var currentHash = window.location.hash;
// Add class to the body based on the current hash state
if (currentHash) {
document.body.classList.add(currentHash.substr(1));
// Remove the ‘#’ character from the hash
}
});
document.addEventListener(‘DOMContentLoaded’, function() {…});: This code waits for the DOM (Document Object Model) to be fully loaded before executing the provided function. This ensures that the JavaScript code doesn’t run until the HTML document is ready.
var currentHash = window.location.hash;: It retrieves the current hash portion of the URL. The hash is the part of the URL that follows the ‘#’ symbol.
if (currentHash) {…}: This checks if there is a hash in the URL. If there is, it proceeds to the next step; otherwise, it does nothing.
document.body.classList.add(currentHash.substr(1));: This adds a class to the body element. The class name is derived from the hash, but the initial ‘#’ character is removed using substr(1). This is done to use the hash value as a class name directly.
So, for example, if the URL is https://example.com/#section1, it will add a class to the body element like this: . This can be useful for applying styles or behaviors based on the current hash state.