Smooth Anchor Scrolling with Header Offset
Intercepts hash-link clicks and scrolls to the target element with a configurable offset for fixed headers.
JavaScriptby SnipCraft
js
(function () {
'use strict';
var OFFSET = 80; // pixels — adjust to match your fixed header height
document.addEventListener('DOMContentLoaded', function () {
document.querySelectorAll('a[href^="#"]').forEach(function (anchor) {
anchor.addEventListener('click', function (e) {
var hash = anchor.getAttribute('href');
if (hash === '#') return;
var target = document.querySelector(hash);
if (!target) return;
e.preventDefault();
var top = target.getBoundingClientRect().top + window.scrollY - OFFSET;
window.scrollTo({ top: top, behavior: 'smooth' });
history.pushState(null, '', hash);
target.setAttribute('tabindex', '-1');
target.focus({ preventScroll: true });
});
});
});
})();#anchor#javascript#navigation#scroll#ux