jaeswift-website/js/nav.js

75 lines
2.5 KiB
JavaScript

/* ─── Dynamic Navigation ─── */
/* Fetches nav items from /api/navigation and renders them */
(function() {
'use strict';
async function loadNavigation() {
const navMenu = document.getElementById('navMenu');
if (!navMenu) return;
try {
const res = await fetch('/api/navigation');
if (!res.ok) throw new Error('Nav API ' + res.status);
const items = await res.json();
// Sort by order
items.sort((a, b) => (a.order || 0) - (b.order || 0));
// Determine current page for active state
const path = window.location.pathname;
// Build nav HTML
let html = '';
items.forEach(item => {
const url = item.url || '/';
const label = (item.label || '').toUpperCase();
// Determine if this link is active
let isActive = false;
if (url === '/' && (path === '/' || path === '/index.html')) {
isActive = true;
} else if (url !== '/' && path.startsWith(url)) {
isActive = true;
}
const activeClass = isActive ? ' active' : '';
// Check if it's an anchor link (homepage sections)
const isAnchor = url.startsWith('#') || url.startsWith('/#');
const href = isAnchor && path !== '/' ? '/' + url.replace(/^\//, '') : url;
html += `<li class="nav-item">`;
html += `<a href="${href}" class="nav-link${activeClass}">${label}</a>`;
html += `</li>\n`;
});
navMenu.innerHTML = html;
} catch (err) {
console.warn('Nav load failed, keeping existing:', err);
// Don't clear - keep any hardcoded fallback
}
}
// Nav toggle (hamburger menu)
function initNavToggle() {
const toggle = document.getElementById('navToggle');
const menu = document.getElementById('navMenu');
if (toggle && menu) {
toggle.addEventListener('click', () => {
menu.classList.toggle('open');
toggle.classList.toggle('active');
});
}
}
// Run on DOM ready
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => {
loadNavigation();
initNavToggle();
});
} else {
loadNavigation();
initNavToggle();
}
})();