Skip to content

Instantly share code, notes, and snippets.

@esedic
Created October 10, 2025 09:38
Show Gist options
  • Select an option

  • Save esedic/0221fd35f37e1113a36abaad6289202d to your computer and use it in GitHub Desktop.

Select an option

Save esedic/0221fd35f37e1113a36abaad6289202d to your computer and use it in GitHub Desktop.

Revisions

  1. esedic created this gist Oct 10, 2025.
    61 changes: 61 additions & 0 deletions scroll.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,61 @@
    // 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}`);
    }
    });
    });
    });