Skip to content

Commit

Permalink
Add location.hash on click event
Browse files Browse the repository at this point in the history
  • Loading branch information
neoformit committed Oct 25, 2024
1 parent 7699e85 commit eafee3d
Showing 1 changed file with 10 additions and 9 deletions.
19 changes: 10 additions & 9 deletions webapp/home/static/home/js/scroll-hash.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -12,7 +12,7 @@ function scrollToElementWithOffset(elementId) {
targetElement.getBoundingClientRect().top + window.scrollY;
window.scrollTo({
top: elementPosition + OFFSET,
behavior: "smooth", // Smooth scroll effect
behavior: "smooth",
});
}
}
Expand All @@ -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);
}
});

0 comments on commit eafee3d

Please sign in to comment.