Scroll Into View

To scroll a scrollable element to get a specific child container in view, can use this javascript code

function scrollToElementWithOffset(elementId, offset = 0, behavior = 'smooth') {
    const element = document.getElementById(elementId);

    if (!element) {
        console.error(`Element with ID "${elementId}" not found.`);
        return;
    }

    // Find the closest scrollable parent
    let scrollableParent = element.parentElement;
    while (scrollableParent) {
        const overflowY = window.getComputedStyle(scrollableParent).overflowY;
        const isScrollable = overflowY === 'auto' || overflowY === 'scroll';
        if (isScrollable) break;
        scrollableParent = scrollableParent.parentElement;
    }

    if (!scrollableParent) {
        console.error("No scrollable parent found.");
        return;
    }

    // Get the element's position relative to the scrollable parent
    const parentRect = scrollableParent.getBoundingClientRect();
    const elementRect = element.getBoundingClientRect();
    const relativeTop = elementRect.top - parentRect.top;

    // Scroll to the adjusted position with offset
    scrollableParent.scrollTo({
        top: scrollableParent.scrollTop + relativeTop - offset,
        behavior: behavior
    });
}

// Call the function with ID 'load' and offset of 20px
scrollToElementWithOffset("location", 20);

To adjust this for your use, the last lines of the code above use (“location”, 20)…you can change location to the element ID of your choosing and the offset value of 20 to your choosing.

For this to work properly, I needed to use a 0.5 second delay from when the container is visible to when running the javascript action, otherwise the offset is not accurate. I did this through a custom trigger with schedule custom trigger.

You can use this function to assist with email notifications that are pertinent to a particular data section. For me, I used URL parameter called ‘link’ and and option set to store the element IDs as option display values to make it simpler.

scrollto-ezgif.com-video-to-gif-converter

This is different than the below, as the below javascript is scrolling to elements not within a parent container other than the page

5 Likes

Wish popups would reset scroll by default…

I first started using the scrollTo for the popup situation. Using the when popup is opened trigger running the javascript so it scrolls up to the top of the popup