end video

This lesson is only accessible in the paid version of the course.

Get access to all lessons 💫 price: 34.99$

If you already have an account click here.

§ Client side routing

Client-side routing with the History API is a technique used in JavaScript to create a single-page application (SPA) that simulates multi-page behavior. Instead of navigating to a new HTML page for each route, the application updates the page content dynamically based on the current URL. The History API provides methods to manipulate the browser history and change the URL without causing a full page refresh.

For example, let's say we have a simple SPA with two pages: a home page and a contact page. We can use the History API to update the page content when the user navigates between pages, like this:

// define the routes and corresponding page content
const routes = {
  '/': '<h1>Home Page</h1>',
  '/contact': '<h1>Contact Page</h1><p>Contact us at hello@example.com</p>'
};

// update the page content when the URL changes
function render() {
  const path = location.pathname;
  const content = routes[path] || routes['/'];
  document.getElementById('app').innerHTML = content;
}

// add event listeners for links to navigate between pages
document.getElementById('home-link').addEventListener('click', function(event) {
  event.preventDefault();
  window.history.pushState(null, null, '/');
  render();
});

document.getElementById('contact-link').addEventListener('click', function(event) {
  event.preventDefault();
  window.history.pushState(null, null, '/contact');
  render();
});
questionnaire
discussion

Materials

Materials related to the lesson:
Files associated with the lesson

Materials

Next: Loading resources dynamically(05:25)

To the lesson →