Last active
November 23, 2024 10:59
-
-
Save H-ymt/5d2efe5372bc10087bfb91e06aaf81be to your computer and use it in GitHub Desktop.
ヘッダーの高さを取得してスムーススクロールさせるJS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
document.addEventListener("DOMContentLoaded", () => { | |
const handleInternalLink = (e) => { | |
e.preventDefault() | |
const targetId = e.currentTarget.getAttribute("href").slice(1) | |
const targetElement = document.getElementById(targetId) | |
if (targetElement) { | |
const headerHeight = document.querySelector("header")?.offsetHeight || 0 | |
const scrollToPosition = targetElement.offsetTop - headerHeight | |
window.scrollTo({ | |
top: scrollToPosition, | |
behavior: "smooth", | |
}) | |
} | |
} | |
const links = document.querySelectorAll("a[href^='#']") | |
for (const link of links) { | |
link.addEventListener("click", handleInternalLink) | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment