Created
October 10, 2025 09:38
-
-
Save esedic/0221fd35f37e1113a36abaad6289202d to your computer and use it in GitHub Desktop.
Add an offset to scrolling anchor links
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
| // Method 1 | |
| window.addEventListener('load', function() { | |
| var theHash = location.hash; | |
| // add offset only for specific hashes | |
| var hashes = ['#project-togo', '#project-colombia-visajes', '#project-colombia-izquierdo', '#project-yemen', '#project-tansania']; | |
| if (hashes.includes(theHash)) { | |
| window.scrollBy(0, -100); | |
| } | |
| }); | |
| // Method 2 | |
| document.addEventListener('DOMContentLoaded', () => { | |
| const OFFSET = 100; // adjust to match your fixed navbar height | |
| function scrollToHash(hash, smooth = true) { | |
| if (!hash) return; | |
| const target = document.querySelector(hash); | |
| if (target) { | |
| const elementTop = target.getBoundingClientRect().top + window.pageYOffset; | |
| const scrollToPosition = elementTop - OFFSET; | |
| window.scrollTo({ | |
| top: scrollToPosition, | |
| behavior: smooth ? 'smooth' : 'auto' | |
| }); | |
| } | |
| } | |
| // Handle page load with existing hash | |
| if (window.location.hash) { | |
| // Timeout ensures it runs after browser's default jump | |
| setTimeout(() => { | |
| scrollToHash(window.location.hash, false); | |
| }, 0); | |
| } | |
| // Handle clicks on anchor links with hashes | |
| document.querySelectorAll('a[href^="#"]').forEach(anchor => { | |
| anchor.addEventListener('click', (e) => { | |
| const hash = anchor.getAttribute('href'); | |
| if (hash.length > 1) { | |
| e.preventDefault(); | |
| history.pushState(null, '', hash); | |
| scrollToHash(hash); | |
| } | |
| }); | |
| }); | |
| // Handle links pointing to current page with hash (e.g. /projects#section) | |
| document.querySelectorAll(`a[href*="#"]`).forEach(anchor => { | |
| anchor.addEventListener('click', (e) => { | |
| const href = anchor.getAttribute('href'); | |
| const [urlPart, hash] = href.split('#'); | |
| if (hash && (window.location.pathname === urlPart || urlPart === '')) { | |
| e.preventDefault(); | |
| history.pushState(null, '', `#${hash}`); | |
| scrollToHash(`#${hash}`); | |
| } | |
| }); | |
| }); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment