A simple vanilla JavaScript router.
A simple dependency-free minimalistic JavaScript router
data-navigo
HTML attributeDrop the following into your page:
<script src="//unpkg.com/navigo"></script>
or via npm/yarn:
> npm install navigo --save
> yarn add navigo -S
import Navigo from 'navigo'; // When using ES modules.
const router = new Navigo('/');
The constructor of the library accepts a single argument - the root path of your app. If you host your project at https://site.com/my/awesome/app
, your root path is /my/awesome/app
. Then you have to define your routes.
router.on('/my/awesome/app', function () {
// do something
});
At the end you have to trigger the resolving logic:
router.resolve();
After that when you need a page change call the navigate
method. This one changes the URL and (by default) triggers resolve
.
router.navigate('/about');
Add data-navigo
attribute to your page links and they'll be transformed into navigate
callers.
<a href="/about/contacts" data-navigo>Contacts</a>
Checkout the online playground to see it in action.
> yarn dev
> yarn build
> yarn test
> yarn test-watch