Skip to content

Instantly share code, notes, and snippets.

@H-ymt
Last active November 23, 2024 10:59
Show Gist options
  • Save H-ymt/5d2efe5372bc10087bfb91e06aaf81be to your computer and use it in GitHub Desktop.
Save H-ymt/5d2efe5372bc10087bfb91e06aaf81be to your computer and use it in GitHub Desktop.
ヘッダーの高さを取得してスムーススクロールさせるJS
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