バニラJSでスムーススクロールを実装【ヘッダー固定対応】
記事内に商品プロモーションを含む場合があります
バニラJSでスムーススクロールを実装を実装しました。
headerが固定されている場合、スクロールの位置が被ってしまいますが、header部分にclass「.header」を追加することで、headerの高さ分を配慮するか、配慮しないかを対応できます。
設定は、以下のコードのこの部分を変更することでheaderの高さを配慮するか、しないか設定可能です。
const headerHeightOption = 0; // 0: ヘッダーの高さを配慮しない, 1: headerの高さを配慮する
// ページ内リンクに対するスムーズスクロール
const smoothScrollTrigger = document.querySelectorAll('a[href^="#"]');
const headerHeightOption = 0; // 0: ヘッダーの高さを配慮しない, 1: headerの高さを配慮する
for (let i = 0; i < smoothScrollTrigger.length; i++) {
smoothScrollTrigger[i].addEventListener("click", (e) => {
e.preventDefault();
let href = smoothScrollTrigger[i].getAttribute("href");
let targetElement = document.getElementById(href.replace("#", ""));
const rect = targetElement.getBoundingClientRect().top;
const offset = window.pageYOffset;
const gap = headerHeightOption === 1 ? document.querySelector(".header").offsetHeight : 0;
const target = rect + offset - gap;
window.scrollTo({
top: target,
behavior: "smooth",
});
});
}
// 別ページへのリンクに対するスムーズスクロール
const smoothScrollToTarget = (targetElement) => {
const rect = targetElement.getBoundingClientRect().top;
const offset = window.pageYOffset;
const gap = headerHeightOption === 1 ? document.querySelector(".header").offsetHeight : 0;
const target = rect + offset - gap;
window.scrollTo({
top: target,
behavior: "smooth",
});
};
// ページ読み込み時にURLのハッシュ部分の要素へスムーズスクロール
window.addEventListener("load", () => {
const hash = window.location.hash;
if (hash) {
const targetElement = document.getElementById(hash.replace("#", ""));
if (targetElement) {
smoothScrollToTarget(targetElement);
}
}
});
// 別ページへのリンクをクリックしたときのスムーズスクロール
document.addEventListener("click", (e) => {
const targetElement = e.target;
if (targetElement.tagName === "A" && targetElement.getAttribute("href").startsWith("#")) {
e.preventDefault();
const href = targetElement.getAttribute("href");
const hash = href.replace("#", "");
const targetElementOnDifferentPage = document.getElementById(hash);
if (targetElementOnDifferentPage) {
smoothScrollToTarget(targetElementOnDifferentPage);
// URLのハッシュ部分を更新(ブラウザの履歴に追加)することで、スムーズスクロールした位置に戻るときに対応する要素に移動します。
history.pushState(null, null, href);
}
}
});
ABOUT ME