Spaces:
Running
Running
// Script for dynamic content loading | |
document.addEventListener('DOMContentLoaded', function() { | |
// Content container where pages will be loaded | |
const contentContainer = document.getElementById('dynamic-content'); | |
if (!contentContainer) return; | |
// Function to load page content | |
window.loadPage = function(pageName) { | |
// Add .html extension if not provided | |
if (!pageName.endsWith('.html')) { | |
pageName += '.html'; | |
} | |
// Fetch the requested page | |
fetch(pageName) | |
.then(response => { | |
if (!response.ok) { | |
throw new Error(`HTTP error! Status: ${response.status}`); | |
} | |
return response.text(); | |
}) | |
.then(html => { | |
// Extract the content from the HTML (assuming each page has its main content in a div) | |
const parser = new DOMParser(); | |
const doc = parser.parseFromString(html, 'text/html'); | |
// Look for the main content in the page | |
// This assumes each page has its main content within a main tag or a specific div | |
const mainContent = doc.querySelector('main') || doc.querySelector('.min-h-screen'); | |
if (mainContent) { | |
// Replace the content in the container | |
contentContainer.innerHTML = mainContent.innerHTML; | |
// Update the URL without refreshing | |
history.pushState({page: pageName}, '', `?page=${pageName}`); | |
// Scroll to top | |
window.scrollTo(0, 0); | |
// Update active state in navigation | |
updateActiveNavLink(pageName); | |
} else { | |
contentContainer.innerHTML = '<p>Could not load content. Please try again.</p>'; | |
} | |
}) | |
.catch(error => { | |
console.error('Error loading page:', error); | |
contentContainer.innerHTML = `<p>Error loading page: ${error.message}</p>`; | |
}); | |
return false; // Prevent default link behavior | |
}; | |
// Function to update active state in navigation | |
function updateActiveNavLink(pageName) { | |
// Remove active class from all nav links | |
document.querySelectorAll('.nav-link').forEach(link => { | |
link.classList.remove('active', 'text-accent'); | |
link.classList.add('text-gray-600'); | |
}); | |
// Add active class to current page link | |
const activeLink = document.querySelector(`.nav-link[data-page="${pageName.replace('.html', '')}"]`); | |
if (activeLink) { | |
activeLink.classList.add('active', 'text-accent'); | |
activeLink.classList.remove('text-gray-600'); | |
} | |
} | |
// Handle browser back/forward buttons | |
window.addEventListener('popstate', function(event) { | |
if (event.state && event.state.page) { | |
loadPage(event.state.page); | |
} else { | |
// Default to index/home if no state | |
contentContainer.innerHTML = ''; // Reset content | |
location.reload(); // Reload the page to show the default view | |
} | |
}); | |
// Check URL on page load to see if a specific page was requested | |
const urlParams = new URLSearchParams(window.location.search); | |
const pageParam = urlParams.get('page'); | |
if (pageParam) { | |
loadPage(pageParam); | |
} | |
}); | |