Skip to content

Instantly share code, notes, and snippets.

@andrewgremlich
Last active April 19, 2018 02:27
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
A close implementation of client-side routing
<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>
@andrewgremlich
Copy link
Author

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.

@andrewgremlich
Copy link
Author

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