const main = document.querySelector('main');
const pages = Array.from(document.querySelectorAll('[data-page]')); // Must convert to array to preserve elements
- // Display the appropriate page based on the URL path
- function route(path) {
+ // Display the appropriate page based on the URL path (does NOT modify browser history)
+ function showPage(path) {
if (path === '') {
path = 'home';
}
}
}
- // Update the browser history, then route
- function changePage(path) {
+ // Update the browser history, then show page
+ function route(path) {
// If the new page is equal to the current page, don't do anything
if (window.location.pathname.substring(1) === path) {
return;
const url = new URL(path, base);
window.history.pushState({}, '', url);
- route(path);
+ showPage(path);
}
// Set event handlers
for (const router of routers) {
- router.addEventListener('click', e => changePage(e.target.dataset.route));
+ router.addEventListener('click', e => route(e.target.dataset.route));
}
- window.onpopstate = _ => route(window.location.pathname.substring(1));
+ window.onpopstate = _ => showPage(window.location.pathname.substring(1));
- // Route to the current URL (to support direct linking aka deep links)
- route(window.location.pathname.substring(1));
+ // Show the current URL (to support direct linking aka deep links)
+ showPage(window.location.pathname.substring(1));
</script>
</body>