Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support Svelte 4 #6

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open

Conversation

VaelVictus
Copy link

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

@VaelVictus
Copy link
Author

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'});

@kevbook
Copy link

kevbook commented Nov 22, 2023

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

3 participants