How do I link to specific section on another page?

I struggled a bit too with this and apparently, this isn’t allowed in Divhunt (yet) so you need to add some JS that loads AFTER the page is done loading and then perform the “scroll to section”

Say you want to link from page 1 to #id on page 2:

Create link on page1 and create ID on div on page 2 as usual and add this JS code to the “Body End” in “Custom Code”:

<script>
function smoothScrollTo(element, duration = 1200) {
    const targetPosition = element.getBoundingClientRect().top;
    const startPosition = window.pageYOffset;
    const distance = targetPosition - startPosition;
    let startTime = null;

    function animation(currentTime) {
        if (startTime === null) startTime = currentTime;
        const timeElapsed = currentTime - startTime;
        const ease = easeInOutCubic(timeElapsed, startPosition, distance, duration);
        window.scrollTo(0, ease);
        if (timeElapsed < duration) requestAnimationFrame(animation);
    }

    function easeInOutCubic(t, b, c, d) {
        t /= d / 2;
        if (t < 1) return c / 2 * t * t * t + b;
        t -= 2;
        return c / 2 * (t * t * t + 2) + b;
    }

    requestAnimationFrame(animation);
}

window.addEventListener('load', function() {
    var hash = window.location.hash;
    if (hash) {
        var element = document.querySelector(hash);
        if (element) {
            smoothScrollTo(element);
        }
    }
});
</script>

This code will capture the hashtag in the URL and run the code if hashtag is available, and do a smooth ease-in/ease-out scroll to the section, linked from another page :ok_hand:t3:

If you want to “snap” directly to your section, use this code instead (no smooth scrolling):

window.addEventListener('load', function() {
    var hash = window.location.hash;
    if (hash) {
        var element = document.querySelector(hash);
        if (element) {
            element.scrollIntoView();
        }
    }
});

These codes are not tied to the specific hashtag so it will work for all your hashtag links no matter the value.

Let me know if it works :+1:t3:

5 Likes