Created
March 17, 2026 15:21
-
-
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.
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
| // 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