Skip to content

Instantly share code, notes, and snippets.

@chellimiller
Created July 19, 2018 00:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chellimiller/5aba9da209dfe00104b220d18f20ce41 to your computer and use it in GitHub Desktop.
Save chellimiller/5aba9da209dfe00104b220d18f20ce41 to your computer and use it in GitHub Desktop.
Super tiny router for a single page app
<!doctype html>
<html>
<title></title>
<meta charset="utf-8">
<style>
page {
display: none;
}
</style>
<body onload="inform()">
<header>
<button onclick="routerRedirect('test')">Test</button>
<a href="#/foo">End</a>
</header>
<main id="outlet"></main>
<page id="example">Example</page>
<page id="bar">Foobar</page>
</body>
<script>
function routerRedirect(url) {
window.location.hash = "/" + url;
}
function updateRouterOutlet(url) {
let page = document.getElementById(getRoute(url));
document.getElementById("outlet").innerHTML = page.innerHTML;
}
window.onhashchange = () => {
updateRouterOutlet(location.hash)
};
function getRoute(url) {
if (url.startsWith('#')) {
url = url.substring(1);
}
if (url.startsWith('/')) {
url = url.substring(1);
}
return routes[url];
}
var routes = {
'test': 'example',
'foo': 'bar',
}
function inform() {
console.log('BODY RELOAD');
}
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment