HRouter.js Javascript Routing Library
23 | HRouter.js is a Simple and Lightweight Javascript Routing Library suitable and designed for Single-page Web Applications 24 | and Mobile HTML5 Applications. 25 |26 |
How to Use & Examples
29 | Download it 30 | HERE and Include it in your Project then create instance of 31 | HRouter object and add routes using the 32 | on( path, handler ) method then activate the routes using the 33 | run method. 34 |35 | 36 |
HRouter#on( path, handler)
38 |This method register routes.
39 |40 | Path : The Route URL, it can be static or dynamic e.g 41 | /about or 42 | /user/:name (required)
. 43 |44 | Handler : The handler function executes each time the route is been visited and it takes 1 argument that is 45 | an Object containing two Objects ( params: Dynamic URL Variables Object, query: URL Query String Object )
46 |HRouter#run()
47 |This method will initiate and add onload and onhashchange listeners to the window then redirect to appropriate route 48 | and execute the route handler function, making the HRouter routes clean and bookmarkable.
49 |Below is an example code that explains the Static, Dynamic and URL Query String concepts. Check the demo of below 50 | code 51 | here. 52 |
53 |
index.html
54 |55 | <!DOCTYPE html> 56 | <html> 57 | <head> 58 | <meta charset="UTF-8"> 59 | </head> 60 | <body> 61 | <div id="hrView"></div> 62 | </body> 63 | <script src="js/HRouter.js"></script> 64 | <script src="js/routes.js"></script> 65 | </html> 66 |67 |
js/routes.js
68 |
69 | /*
70 | HRouter supports method chaining
71 | and 'hrView' is a variable that points to
72 | the block-level element
73 | with id="hrView".
74 | */
75 | var route = new HRouter();
76 | route.on( "/", function( req ){
77 | document.title = "Home";
78 | hrView.innerHTML = "Hello world";
79 | })
80 | .on( "/user/:name", function( req ){
81 | var name = req.params.name;
82 | document.title = "User " + name;
83 | hrView.innerHTML = name + " profile";
84 | })
85 | .on( "/search", function( req ){
86 | var search = req.query.q;
87 | document.title = "Results for " + search;
88 | hrView.innerHTML = "Results for " + search;
89 | });
90 | route.run();
91 |
92 |
93 | Notes:
95 | 1. HRouter.js would redirect to Homepage if no route has been registered for the current URL. 96 |2. You can link between pages using anchor links e.g <a href="#/about">About page</a> .NOTE: The Hash '#' 97 | is a must to put when linking. 98 |
3. You should register static routes before registering almost similar dynamic routes to avoid conflicts e.g 99 | /about before 100 | /:page. 101 |
102 |