I’ve noticed some websites use hash fragments in their URLs to switch between different views or sections. For example, some email services use URLs like example.com/mail/#inbox or example.com/mail/#sent to show different folders.
Another case I’ve seen is on validation websites. They use hashes like #validate_by_uri or #validate_by_upload to automatically focus on specific tabs when you load the page.
I’m curious about how this works. Is it all done with JavaScript? Does the script check the URL hash and then change the page content accordingly? Also, how do they stop the page from scrolling to where the hash would normally point?
If anyone could explain the process or point me to some resources, that would be great. I’d love to implement something similar in my own web app.
Having worked on a project that used hash-based navigation, I can say it’s mainly a matter of leveraging JavaScript’s ability to listen for changes in the URL. The idea is to attach an event listener to the window object to catch the ‘hashchange’ event. When the event fires, your script can read the current hash (using window.location.hash) and update the page content accordingly.
To prevent the browser’s default behavior of scrolling to an element that matches the hash, you can manage the scroll restoration manually, either by preventing the event’s default action or by adjusting the document’s scroll behavior during the update. Using a library like History.js could further simplify cross-browser compatibility and enhance the navigation experience.
yo, hash-based nav is pretty slick. basically u listen for changes in the URL hash with javascript. when it changes, u update the page content without a full reload. it’s all about that smooth user experience, ya know? u can use the History API to make it even cooler. just remember to handle the initial page load too!
I’ve successfully used hash-based navigation in my projects by monitoring changes to the URL’s hash fragment. In my implementation, I attach an event listener to the window to catch the hashchange event. Once the hash changes, my code reads window.location.hash and updates the displayed content accordingly without reloading the page. To prevent the default scrolling behavior, I reset the scroll position after updating the content or configure scrollRestoration. This approach also considers the initial page load, ensuring a consistent and smooth user experience.