Router — DIY

Ran Wahle
ranwahle
Published in
2 min readApr 21, 2019

As a developer, App navigation always seemed as the one thing that makes the different between a Single Page Application and some smart screen that can do some server requests. Therefore I have always considered routing part of each library / framework, to be some kind of a magic I couldn’t do without.

However, always, deep down, I have felt that it is something I really could do myself, and because I’m not that smart, I feel that this is something every developer can do.

In the small video below (Excuse my pure graphic design and picture selection) you may see a screen recording of an app, replacing images by their number written in the url, while its code, which I’m demonstrating, written in pure javascript.

Routing in action

What should we do to achieve that?

There are two behaviors we need to alter when developing a router
1. Alter the anchor element’s behavior.
2. Alter the browser behavior when history changes

Instead of the above two default behavior, implement your routing mechaism.

How do I alter the anchor elements’ behavior?

Easy, just add an onclick event and prevent its default behavior

this.onclick = evt => {
evt.preventDefault();
// do your magic
};

Ok, and what should I do with the browser?

The same, capture its history popstate event

window.onpopstate = (e) => {
// do your magic
};

And what about the magic?

Here it begins.

--

--