Skip to content

Instantly share code, notes, and snippets.

@joelalejandro
Created January 5, 2020 21:19
Show Gist options
  • Save joelalejandro/e843eaada3793d85e91bf97b4ad98a9f to your computer and use it in GitHub Desktop.
Save joelalejandro/e843eaada3793d85e91bf97b4ad98a9f to your computer and use it in GitHub Desktop.
A chia seed sized router for static websites.
/**
* Chia Router
* A chia seed sized router for static websites.
*
* This simple client-side router allows to switch visibility
* for section elements decorated with a [data-route] attribute.
*
* Let's say you have a couple of sections on your menu:
*
* <nav>
* <a href="#/">Home</a>
* <a href="#/bio">Biography</a>
* <a href="#/contact">Contact</a>
* </nav>
*
* And the content for the page:
*
* <section data-route="home">Home</section>
* <section data-route="bio">Home</section>
* <section data-route="contact">Home</section>
*
* Further along the page, you instantiate ChiaRouter:
*
* new ChiaRouter({
* defaultRoute: "home"
* });
*
* And magically, there you have it, a very simple, chia-sized router :D
*/
function ChiaRouter(options) {
var router = this;
// Where we are right now.
this.currentRoute = options.defaultRoute;
// The route where the site starts.
this.defaultRoute = options.defaultRoute;
// An event handler for doing fancy stuff when the route changes.
this.onRouteChanged = options.onRouteChanged || function noop() {};
// A selector of all available sections.
this.pages = options.pages || document.querySelectorAll("[data-route]");
// The function that performs all routing operations. You can either
// call it manually or let it do its job while listening to the HashChangeEvent.
this.route = function route(/** @type HashChangeEvent|string */ eventOrRoute) {
var newRoute = eventOrRoute || { newURL: window.location.href };
if ('newURL' in newRoute) {
newRoute = newRoute.newURL.split("#/")[1] || options.defaultRoute;
}
router.pages.forEach(function (/** @type HTMLElement */ page) {
page.style.display = page.dataset['route'] === newRoute ? 'block' : 'none';
});
router.onRouteChanged(this.currentRoute, newRoute);
router.currentRoute = newRoute;
if (router.currentRoute === router.defaultRoute) {
window.location.replace("/#");
}
}
window.addEventListener("hashchange", this.route);
this.route();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment