svelte-scrollto-element icon indicating copy to clipboard operation
svelte-scrollto-element copied to clipboard

Support Svelte 4

Open VaelVictus opened this issue 2 years ago • 2 comments

I can confirm everything's working as expected in Svelte 4.

VaelVictus avatar Jul 19 '23 03:07 VaelVictus

Unfortunately I could no longer wait for this to hit npm, and built this with the help of AI. Hopefully it will be of use to anyone who doesn't need the extra functionality from this package.

const animateScroll = {
        getAbsoluteTop: function(element) {
            let top = 0;
            while (element) {
                top += element.offsetTop || 0;
                element = element.offsetParent;
            }
            return top;
        },
        scrollTo: function({element, duration = 1000, offset = 0, container = 'body'}) {
            const containerElement = container === 'body' ? document.documentElement : document.querySelector(container);
            const containerTop = this.getAbsoluteTop(containerElement);
            const start = containerElement.scrollTop;
            const target = this.getAbsoluteTop(element) - containerTop + offset;
            const distance = target - start;
            const startTime = performance.now();
            let nextStep;

            const easeInOutQuad = function(time) {
                time /= duration / 2;
                if (time < 1) return distance / 2 * time * time + start;
                time--;
                return -distance / 2 * (time * (time - 2) - 1) + start;
            };

            let scroll = (currentTime) => {
                const timeElapsed = currentTime - startTime;
                nextStep = easeInOutQuad(timeElapsed);

                containerElement.scrollTop = nextStep;

                if(timeElapsed < duration) {
                    requestAnimationFrame(scroll);
                }
            };
            
            requestAnimationFrame(scroll);
        }
    };

Usage animateScroll.scrollTo({element: document.querySelector(`#your_element`), duration: 750, offset: -95, container: '#your_container'});

VaelVictus avatar Jul 27 '23 03:07 VaelVictus

You can just use the native scrollIntoView now https://svelte.dev/repl/e073dc93fb3347848062a531271e497f

kevbook avatar Nov 22 '23 17:11 kevbook