Skip to content

Instantly share code, notes, and snippets.

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
What would you like to do?
A close implementation of client-side routing
<style media="screen">
nav p {
background-color: #c1c1c1;
cursor: pointer;
.output {
display: none;
<div class="oneSec output">
Here is oneSec
<div class="twoSec output">
Here is twoSec
<div class="threeSec output">
here is threeSec
<script type="text/javascript">
function changePage(text, push) {
document.querySelectorAll(`.output`).forEach(e => { = 'none';
document.querySelector(`.${text}`).style.display = 'block';
if (push)
history.pushState({ route: `/${text}/` }, '', `/${text}/`)
function handleNewState(e) {
let 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 =,
if (clicked.localName !== "nav") {
text = clicked.innerText;
changePage(text, true)
Copy link

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.

Copy link

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