Skip to content

Instantly share code, notes, and snippets.

@gordonbrander
Last active April 30, 2022 01:26
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gordonbrander/62eb1076febbde1576b0 to your computer and use it in GitHub Desktop.
Save gordonbrander/62eb1076febbde1576b0 to your computer and use it in GitHub Desktop.
route.js: a history.pushState microrouter without the routing fluff.
// Microrouter based on history.pushState.
// All thrills, no frills.
// Usage:
//
// var h = urlstate(callback);
// h.push('#foo')
function urlstate(callback) {
// Since `history.pushState` doesn't fire `popstate`, we can use this function
// instead. Will update history state and call `callback` with currently
// showing `url`.
function push(fragment, title) {
history.pushState(null, null, fragment || window.location.pathname);
callback(document.location.href);
if (title) document.title = title;
return document.location.href;
}
// Same goes for `history.replaceState`.
function replace(fragment, title) {
history.replaceState(null, null, fragment || window.location.pathname);
callback(document.location.href);
if (title) document.title = title;
return document.location.href;
}
function onpopstate() {
// Fire callback whenever a true history change happens (e.g. user
// presses back button).
callback(document.location.href);
}
// Call callback on initialization, since Firefox doesn't fire `popstate` on
// window load. Safari does, however. It's assumed you're doing stateless
// routing, so a double-hit to callback on startup shouldn't hurt.
callback(document.location.href);
// Bind event listener.
window.addEventListener('popstate', onpopstate);
return { push: push, replace: replace };
}
@brettz9
Copy link

brettz9 commented Apr 30, 2022

Very nice... License?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment