I’ve noticed some websites use hash fragments in their URLs to switch between different views or sections. For example, some email services use #inbox or #starred to show different folders. Another instance is on validation websites where #validate_by_uri or #validate_by_upload focus on specific tabs.
I’m curious about how this works. Is it done with JavaScript? How does the page detect the hash and change the view accordingly? Also, how do you stop the page from jumping to the hash position?
Here’s a basic example of what I mean:
function switchView(hash) {
// How would this function work?
if (hash === '#inbox') {
showInbox();
} else if (hash === '#starred') {
showStarred();
}
}
// How to call this when the page loads?
Any tips or explanations would be really helpful. Thanks!
hey, i’ve used this technique before! it’s pretty neat. basically, you listen for the ‘hashchange’ event and update your view accordingly. here’s a quick example:
window.onhashchange = () => {
const hash = window.location.hash;
if (hash === ‘#inbox’) showInbox();
else if (hash === ‘#starred’) showStarred();
};
call this on page load too. prevents jumping by using javascript to show/hide content instead of actual page anchors.
I’ve implemented this technique in a few projects, and it’s quite effective for creating single-page applications. The key is to use the ‘hashchange’ event listener, as Isaac_Cosmos mentioned, but I’d like to add a few practical tips.
First, make sure to handle the initial page load correctly. You can do this by calling your switchView function immediately after setting up the event listener:
window.addEventListener(‘hashchange’, handleHashChange);
handleHashChange(); // Call this immediately to handle initial load
function handleHashChange() {
switchView(window.location.hash);
}
Also, consider using a switch statement instead of if-else for better readability when you have multiple views:
function switchView(hash) {
switch(hash) {
case ‘#inbox’:
showInbox();
break;
case ‘#starred’:
showStarred();
break;
default:
showDefault();
}
}
This approach has served me well in various projects, providing a clean and efficient way to handle view changes without full page reloads.
You’re on the right track with your JavaScript approach. The key is to use the window.onhashchange
event listener. Here’s how you can implement it:
window.onhashchange = function() {
switchView(window.location.hash);
};
function switchView(hash) {
if (hash === '#inbox') {
showInbox();
} else if (hash === '#starred') {
showStarred();
}
}
Call switchView(window.location.hash)
when the page loads to handle the initial hash. To prevent jumping, use event.preventDefault()
in your click handlers for hash links.
For a smoother UX, consider using the History API instead. It allows the URL to change without a page reload and avoids unwanted jumps. Look into pushState()
and popstate
events for more advanced routing.