hashchange Syncs State To The URL Fragment
Map location.hash to view state with a hashchange listener so every tab change is a shareable URL and back navigation rewinds the view.
Code
const TABS = new Set(['overview', 'logs', 'settings']);
function renderView() {
// '#/logs' style fragments keep the scheme forward-compatible
const raw = location.hash.slice(1).replace(/^\//, '');
const view = TABS.has(raw) ? raw : 'overview';
console.log('render:', view);
return view;
}
// hashchange fires after the fragment changes — back/forward included.
window.addEventListener('hashchange', renderView);
// Navigating to an unknown fragment falls back to the default view.
location.hash = '#/logs';
const first = renderView();
location.hash = '#/does-not-exist';
const second = renderView();
// Direct assignment rewinds the entry so the browser history stays coherent.
location.hash = '#/overview';
const third = renderView();
console.log('views:', first, second, third);How the logic moves
hashchange Syncs State To The URL Fragment comes down to the function renderView.
Points of care
- No third-party code is loaded at any point while this runs.
- This is browser-side code —
windowwill not resolve in Node.
Using it
Entry signature: function renderView()
The run emits 2 labeled sections — render:, views: — one per step.
Quoted highlights
const TABS = new Set(['overview', 'logs', 'settings']);
window.addEventListener('hashchange', renderView);
Interactive Tools for This Topic
DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.URL Pattern MatcherTest Express-style URL patterns with :param and wildcard segments against concrete paths and extract the captured parameter values.Base64url CodecEncode and decode Base64url, the URL- and filename-safe variant that swaps + and / for - and _ and omits padding.Nano ID GeneratorGenerate URL-safe Nano ID strings with a configurable length and alphabet using the Web Crypto API.
FAQ
- Does hashchange Syncs State To The URL Fragment run in plain Node.js?
- No — it touches `window`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.
Report a problem with this exampleOpens a pre-filled issue on GitHub.