<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Client-Side Routing Basic Demo</title>
<link rel="stylesheet" href="style.css">
<script src="script.js" defer></script>
</head>
<body>
<nav>
<a href="/home">Home</a>
<a href="/about">About</a>
<a href="/contact">Contact</a>
</nav>
<main>
<section id="home">Welcome to the Home page!</section>
<section id="about" hidden>Learn more About us!</section>
<section id="contact" hidden>Get in touch with us via Contact page!</section>
</main>
</body>
</html>
body {
padding: 40px
}
nav a {
margin-right: 10px;
text-decoration: none;
color: blue;
padding: 10px;
background-color: #DDD;
}
main {
margin-top: 40px;
padding: 20px 0;
border-top: 1px solid #DDD;
}
// Function to update the visibility of sections based on the current path
function showSection(path) {
document.querySelectorAll('section').forEach(sec => sec.hidden = true);
if (path === '/about') {
document.getElementById('about').hidden = false;
} else if (path === '/contact') {
document.getElementById('contact').hidden = false;
} else {
document.getElementById('home').hidden = false;
}
}
// Initial load: Show section based on the current URL
showSection(window.location.pathname);
// Event listener for navigation
document.querySelectorAll('nav a').forEach(link => {
link.addEventListener('click', function(e) {
e.preventDefault(); // Prevent default link behavior
const path = this.getAttribute('href');
history.pushState({}, '', path); // Update the URL without reloading
showSection(path); // Update visible section
});
});
// Handle browser back/forward navigation
window.addEventListener('popstate', function() {
showSection(window.location.pathname);
});
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.