From eafee3db782fd9a77d9d4a2016af73d26d2d5ab5 Mon Sep 17 00:00:00 2001 From: Cameron Hyde Date: Fri, 25 Oct 2024 13:24:31 +1000 Subject: [PATCH] Add location.hash on click event --- webapp/home/static/home/js/scroll-hash.js | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/webapp/home/static/home/js/scroll-hash.js b/webapp/home/static/home/js/scroll-hash.js index 4ee7c53..bc43960 100644 --- a/webapp/home/static/home/js/scroll-hash.js +++ b/webapp/home/static/home/js/scroll-hash.js @@ -2,7 +2,7 @@ // hash navigation. This prevents the browser from scrolling past the target // element. -const OFFSET = -120; // Custom offset (in px) +const OFFSET = -120; // Set offset from scroll target (px) function scrollToElementWithOffset(elementId) { const targetElement = document.getElementById(elementId); @@ -12,7 +12,7 @@ function scrollToElementWithOffset(elementId) { targetElement.getBoundingClientRect().top + window.scrollY; window.scrollTo({ top: elementPosition + OFFSET, - behavior: "smooth", // Smooth scroll effect + behavior: "smooth", }); } } @@ -21,23 +21,24 @@ function scrollToElementWithOffset(elementId) { document.querySelectorAll("a").forEach((link) => { if (link.getAttribute("href").startsWith("#")) { link.addEventListener("click", function (event) { - event.preventDefault(); // Prevent default anchor scroll - const targetId = this.getAttribute("href").substring(1); // Get the target ID - scrollToElementWithOffset(targetId); // Scroll with custom behavior + event.preventDefault(); + const targetId = this.getAttribute("href").substring(1); + scrollToElementWithOffset(targetId); + window.location.hash = targetId; }); } }); // Handle URL hash change (for direct navigation to #elementId) window.addEventListener("hashchange", function () { - const hash = window.location.hash.substring(1); // Get the current hash (without the #) - scrollToElementWithOffset(hash); // Scroll with custom behavior + const hash = window.location.hash.substring(1); + scrollToElementWithOffset(hash); }); // Scroll on page load if the URL contains a hash window.addEventListener("load", function () { - const hash = window.location.hash.substring(1); // Get the current hash (without the #) + const hash = window.location.hash.substring(1); if (hash) { - scrollToElementWithOffset(hash); // Scroll with custom behavior + scrollToElementWithOffset(hash); } });