Single-page routes, by hand
The whole Cosmos UI exists, but it "lives" on one URL — you can't share a link to a specific picture, and the browser Back button does nothing. We'll fix that with a router by hand — no framework.
Since this is a single-page app (SPA), there's no real navigation between HTML files. Instead we use the URL hash (the part after #):
#/ → home
#/gallery → gallery
#/collection → collection
#/apod/2026-07-11 → one picture (shareable, bookmarkable)
The router is just a table of "name → function" and one event:
onRoute('gallery', renderGallery);
onRoute('detail', renderDetail);
window.addEventListener('hashchange', handleRoute);
The brilliance is in the hashchange event. It fires both when you click a link with a # and when you press the browser's Back/Forward. So the Back button works for free — we do nothing extra. That's the key insight.
Three capabilities we'll get:
- Deep links.
#/apod/2026-07-11opened fresh (with no data) must fetch that one picture itself. - URL-synced search.
#/gallery?q=moon— the search becomes a shareable link and survives a refresh. - A working Back button. Browse the gallery → a detail → back, and the browser takes you back.
And two traps: how not to create a hundred history entries per search keystroke (replaceState), and why you never split ?q=moon&days=30 by hand (URLSearchParams).