Master Routing in HTML JavaScript with Easy Step by Step Guide

In the realm of web development, the seamless navigation between different sections or pages of your website is achieved through routing. While this concept is intrinsic to server-side languages like PHP or Node.js, it's also possible to implement routing in the client-side using HTML and JavaScript, specifically with libraries like histories and hashchange events.

JavaScript Full Notes Every Beginner Must Save 💡
JavaScript Full Notes Every Beginner Must Save 💡

Before delving into the intricate details, let's first understand why you might want to use client-side routing. It's particularly useful for creating Single Page Applications (SPAs), where the entire application runs on a single page without needing to reload or render the entire page on every user action. This results in faster and more dynamic user experiences.

Next.js useRouter Hook Explained | Dynamic Routing Made Easy 🚀
Next.js useRouter Hook Explained | Dynamic Routing Made Easy 🚀

Understanding the Process

Client-side routing relies heavily on the browser's history API and the hashchange event. The history API allows you to manipulate the browser history stack, essentially enabling users to navigate back and forth between different states or pages on your website. The hashchange event, on the other hand, fires whenever the hash part of the URL (the part after the '#') changes, which allows your JavaScript to respond to changes in the address bar without reloading the page.

Express.js Routing Explained Visually — How URL Paths Hit Your Routes
Express.js Routing Explained Visually — How URL Paths Hit Your Routes

To illustrate, consider a typical user scenario: a visitor lands on your website's homepage, spends some time exploring your blog posts, and then visits a specific post. Using client-side routing, you can dynamically update the URL's hash part to '#blog-post-123' without disrupting the user's flow, thus creating a cleaner and more intuitive URL structure.

Implementing Basic Routing

Next.js API Routes | Quick & Easy Setup 🧩
Next.js API Routes | Quick & Easy Setup 🧩

Implementing a basic routing mechanism entailsinitializing a new 'history' object and observing changes in the URL's hash. Here's a simple example:

  • Initialize the history object: const/history = History.create({state: {}})/code>
  • Listen for hash changes: window.addEventListener('hashchange', handleRouteChange)
  • In your event handler, determine which route the user has transitioned to and update your application's state accordingly: const handleRouteChange = () => {}

The above code sets up a basic routing system that updates the application's state based on changes in the URL hash. The responsibilities of the 'handleRouteChange' function are to analyze the current hash and, based on it, render or update the appropriate content.

Learn JavaScript in the Right Order 🚀
Learn JavaScript in the Right Order 🚀

Matching Routes

To match different routes and handle each appropriately, you might use regular expressions or a more sophisticated algorithm. One common approach is defining a mapping of routes to their corresponding functions that can handle user requests. For instance:

  • const routes = { '/' : home, '/about': about,'/blog': blog };
  • Next, in the handleRouteChange function, use these routes to match and call the appropriate function:
  • const path = window.location.hash.substr(1); function active() {return routes[path]() || () => {};} active();
Web Development Roadmap for Beginners | Step-by-Step Guide
Web Development Roadmap for Beginners | Step-by-Step Guide

Using this system, when the user navigates between different parts of your web app by changing the hash value, the appropriate function will be called to handle the request.

Handling Multiple Route Parameters

HTML,CSS JAVASCRIPT cheatsheet
HTML,CSS JAVASCRIPT cheatsheet
login form html css
login form html css
JavaScript Cheatsheet for Beginners | Learn JS Fast (One-Page Guide)
JavaScript Cheatsheet for Beginners | Learn JS Fast (One-Page Guide)
JavaScript Roadmap for Beginners, Intermediate and Experts
JavaScript Roadmap for Beginners, Intermediate and Experts
JavaScript Roadmap 2026 | Complete Guide to Become a JavaScript Developer 🚀
JavaScript Roadmap 2026 | Complete Guide to Become a JavaScript Developer 🚀
Focus | HTML CSS JavaScript
Focus | HTML CSS JavaScript
Understanding routing of expressJS in Node.JS
Understanding routing of expressJS in Node.JS
How Express.js Routing Works (Beginner to Advanced Guide)
How Express.js Routing Works (Beginner to Advanced Guide)
Learning JavaScript Roadmap
Learning JavaScript Roadmap
an info sheet with different types of web pages
an info sheet with different types of web pages
JavaScript loops by Duomly
JavaScript loops by Duomly
JavaScript Roadmap for Beginners 2026
JavaScript Roadmap for Beginners 2026
JavaScript Tips to Change Border Radius & Background Color
JavaScript Tips to Change Border Radius & Background Color
sunset evening using html css javascript
sunset evening using html css javascript
HTML Cheat Sheet 📄✨ Quick Guide for Beginners
HTML Cheat Sheet 📄✨ Quick Guide for Beginners
Create Image Accordion Slider With HTML CSS And JavaScript
Create Image Accordion Slider With HTML CSS And JavaScript
JavaScript Arrays: Master Data Storage & Manipulation 📊
JavaScript Arrays: Master Data Storage & Manipulation 📊
Coding Roadmap for Beginners 2026
Coding Roadmap for Beginners 2026
an image of a blue screen with the words html structure in white letters on it
an image of a blue screen with the words html structure in white letters on it
a yellow background with the words, why use client - side routing?
a yellow background with the words, why use client - side routing?

sometimes, you might need to handle routes with multiple parameters. For example, you might have a blog where each post is identified by an ID. In this case, your route could look something like '#blog-post-123'. To extract these parameters programmatically, you could use regular expressions:

To route to a different post, you could use the following URL structure: '#blog-post-123'. The '123' represents the ID of the blog post. Here, you'd use regular expressions to find and extract this ID:

  • const path = window.location.hash.substr(1); const match = path.match('/blog-post-(\d+)'); if (match) {blogpost(match[1]);}

The above code matches the path against a regular expression, then extracts and uses the blog post ID if it matches the format.

Handling Query Strings

Similar to blog post IDs, you might need to handle queries in your route URLs. Queries are parameters you append on the URL for sorting, filtering, or any other use case. Here's an example of how you might handle a sorting query: '#blog-post-123?sort=recent'.

You could use a small util function to parse out the query string and turn it into an object:

  • const queryString = (path) =>Object.fromEntries(path.match(/[?&].*=/g).map((match) =>match.substr(1).match(/(&|=)/g)));

This function finds all instances of '?' or '&' in the path, and breaks down each instance into a key-value pair, turning the entire string into an object that you can use to sort your blog posts or filter other items.

Mastering client-side routing certainly takes some practice, but the benefits - like more dynamic pages and cleaner URLs - make it well worth the learning. Now that you've a solid understanding of how it works, it's time to start implementing it in your projects. Happy coding!

Related Articles

Html With Link Example Htmlunit Javascript Links To Html Html Library Tulane Htmlunit Java Documentation Convert Html To Zip File Html To Zip Converter Free Easy To Use Html Editor Responsive Html Css Javascript Zim File To Html