Last active
April 19, 2018 02:27
-
-
Save andrewgremlich/7dcf4188443e1ee5e5c6573ff9ebd52b to your computer and use it in GitHub Desktop.
A close implementation of client-side routing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<style media="screen"> | |
nav p { | |
background-color: #c1c1c1; | |
cursor: pointer; | |
} | |
.output { | |
display: none; | |
} | |
</style> | |
</head> | |
<body> | |
<nav> | |
<p>oneSec</p> | |
<p>twoSec</p> | |
<p>threeSec</p> | |
</nav> | |
<div class="oneSec output"> | |
Here is oneSec | |
</div> | |
<div class="twoSec output"> | |
Here is twoSec | |
</div> | |
<div class="threeSec output"> | |
here is threeSec | |
</div> | |
<script type="text/javascript"> | |
function changePage(text, push) { | |
document.querySelectorAll(`.output`).forEach(e => { | |
e.style.display = 'none'; | |
}) | |
document.querySelector(`.${text}`).style.display = 'block'; | |
if (push) | |
history.pushState({ route: `/${text}/` }, '', `/${text}/`) | |
} | |
function handleNewState(e) { | |
let pathname = e.target.location.pathname, | |
firstPick = pathname.split('/')[1], | |
trimmed = pathname.replace(/\//g, '') | |
if (trimmed.length > 0) changePage(firstPick, false) | |
} | |
window.onpopstate = handleNewState | |
window.onload = handleNewState | |
document.querySelector("nav").onclick = e => { | |
let clicked = e.target, | |
text | |
if (clicked.localName !== "nav") { | |
text = clicked.innerText; | |
changePage(text, true) | |
} | |
} | |
</script> | |
</body> | |
</html> |
I figured it out! I just needed to put a condition before the push state in order to traverse backwards always.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The only problem here is that using the back button once only is able to go back one for some reason both with and without the
window.onload
function.Overall, I'm not completely sold that client side routing is vital for SPAs.