document.addEventListener('DOMContentLoaded', function () {
// Adjust this to match your sticky header's height in pixels.
var HEADER_OFFSET = 100;
function scrollToTarget(targetId) {
var target = document.getElementById(targetId);
if (!target) return;
var targetPosition =
target.getBoundingClientRect().top + window.pageYOffset - HEADER_OFFSET;
window.scrollTo({
top: targetPosition,
behavior: 'smooth'
});
}
// Intercept clicks on any link that contains a hash.
document.querySelectorAll('a[href*="#"]').forEach(function (link) {
link.addEventListener('click', function (e) {
var url;
try {
url = new URL(link.href, window.location.origin);
} catch (err) {
return; // malformed href, let default behavior happen
}
var hash = url.hash;
if (!hash) return;
// Normalize paths (strip trailing slashes) for comparison.
var linkPath = url.pathname.replace(/\/$/, '');
var currentPath = window.location.pathname.replace(/\/$/, '');
if (linkPath === currentPath || linkPath === '') {
// We're already on the target page: skip the browser's
// default jump and animate manually instead.
e.preventDefault();
var targetId = hash.substring(1);
scrollToTarget(targetId);
history.pushState(null, null, hash);
}
// Otherwise, it's a link to a different page — let the
// browser navigate there normally. The block below will
// handle the smooth scroll once the new page loads.
});
});
// If the page loads with a hash already in the URL (i.e. someone
// clicked a menu link from a different page), smooth-scroll to
// it instead of leaving the browser's instant jump as-is.
if (window.location.hash) {
setTimeout(function () {
scrollToTarget(window.location.hash.substring(1));
}, 150); // small delay lets layout/images settle first
}
});