Skip to content

Instantly share code, notes, and snippets.

@mujahidi
Created March 17, 2026 15:21
Show Gist options
  • Select an option

  • Save mujahidi/b8539b86b94205c0682f986e362fa250 to your computer and use it in GitHub Desktop.

Select an option

Save mujahidi/b8539b86b94205c0682f986e362fa250 to your computer and use it in GitHub Desktop.
Scroll to element if URL has hash on page load and anchor click, using dynamic .site-header height as offset. Also takes care of offset.
// Scroll to element if URL has hash on page load and anchor click, using dynamic .site-header height as offset
(function($) {
function getHeaderOffset() {
var $header = $('.site-header');
var offset = $header.length ? $header.outerHeight(true) : 0;
if ($('body').hasClass('logged-in')) {
offset += 32;
}
return offset;
}
function scrollToTarget(target) {
var offset = getHeaderOffset();
window.scrollTo({
top: target.getBoundingClientRect().top + window.pageYOffset - offset,
behavior: 'smooth'
});
}
// On page load, scroll if hash exists
if (window.location.hash) {
var target = document.getElementById(window.location.hash.substring(1));
if (target) {
// Use setTimeout to ensure layout is ready
setTimeout(function() {
scrollToTarget(target);
}, 10);
}
}
// On anchor click, scroll to target
document.addEventListener('click', function(e) {
var anchor = e.target.closest('a[href^="#"]:not([href="#"])');
if (anchor) {
var href = anchor.getAttribute('href');
var id = href.slice(1);
var target = document.getElementById(id);
if (target) {
e.preventDefault();
scrollToTarget(target);
}
}
});
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment