HRouter.js - Javascript Routing Made Easy

Download v1.1 View Demo Fork on Github

HRouter.js Javascript Routing Library

HRouter.js is a Simple and Lightweight Javascript Routing Library suitable and designed for Single-page Web Applications and Mobile HTML5 Applications. it also has it own micro-template engine.

How to Use & Examples

HRouter.js doesnt require setup or installation, Download it HERE and Include it in your HTML5 Project then you Register/Add Routes using HRoute function, this function takes 3 Arguments.

Path : The Route URL, it can be static or dynamic e.g /about or /user/:name (required)

.

Page ID : The ID attribute value of the Page Script Tag (required)

Handler : The handler function takes 2 arguments ( param: Dynamic URL Variables Object, query: URL Query String Object ). it can also return Object that would be used in the page template.


Check the live demo of below code Here.

<script type="text/html" id="home">
<h1>Home page</h1>
<p>{% text %}</p>
View: <a href="#/user/Horlahcoded">Horlahcoded's profile</a>
Search: <a href="#/search/?q=HRouter">HRouter</a>
</script>
<script type="text/html" id="profile">
<h1>{% username %} Profile</h1>
<p>This is {% username %} profile<t;/p>
</script>
<script type="text/html" id="search">
<h1>Search results for {% searchQuery %}</h1>
<p>This is search results page</p>
</script>
<div id="hr-app"></div> <script src="HRouter.js"></script> <script>
// home page
HRoute('/', 'home', function (param, query) {
document.title = "Home page";
return {
text: "Hello world from HRouter template"
}
});
// example of 'param' usage : user profile
HRoute('/user/:name', 'profile', function (param, query) {
document.title = param.name + ' Profile';
return {
username: param.name
}
});
// example of 'query' usage : search
HRoute('/search', 'search', function( param, query ) {
document.title = "Search results for " + query.q;
return {
searchQuery: query.q
}
});
</script>

Notes:

1. HRouter.js would redirect to 404 error page if no route was registered/found for the current URL.
2. SCRIPT tag with type "text/html" are used so that the page template will be ignored by browsers making it possible to write anything inside it.
3. HRouter come with a micro-template engine. put any expression or variable between {% and %} e.g {% name.toUpperCase() %}. it support ternary operators, math operations, variable and function declaration, method/function calls and other things you can put in eval() function.
4. You can link between pages using anchor links e.g <a href="#/about">About page</a> .NOTE: The Hash '#' is a must to put when linking.
5. HTML Block element e.g DIV, SECTION etc. with ID attribute value of "hr-app" will be used to render route pages.
Thanks, Check out my other projects here.