Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Framer Motion infinite scroll slider/carousel

framer-motion lets you add drag="x" to a motion element which you can then drag along the x-axis. This is achieved by changing transform: translateX(...px) based on how far the user dragged.

This allows to easily create a slider.

There are some examples about how to achieve an infinte carousel slider (no start / no end - last item is followed by the first again) with framer-motion - but only with one item visible.

Is there a way to create an infinite carousel slider with multiple items visible at the same time?

I need to use framer-motion because the slider items have to be animated with framer-motion and framer-motion animations doesn't work with other slider libraries like Splide.

Other frameworks like Splide have cloned items left and right to the original items in the slider and the translateX coordinate resets when the end of the original items is reached. Demonstration: https://i.sstatic.net/yfV61.jpg

As far as I know manipulating the translateX of a motion element is only possible via the useAnimation hook which doesn't work while the user is dragging.

like image 639
Johannes Avatar asked Dec 06 '25 07:12

Johannes


1 Answers

This is in sveltekit but you can translate it into React easily, the principal is what matters.

// Script

const images = [
    '/images/1.jpeg',
    '/images/2.jpeg',
    '/images/3.jpeg',
    '/images/4.jpeg',
    '/images/5.jpeg'
];

let innerHeight: number;

// Svelte

<svelte:window bind:innerHeight />
<ul class='space-y-2'>
    {#each Array(2) as _} 
        {#each images as src}
            <Motion
                let:motion
                transition={{ duration: 5, ease: 'linear', repeat: Infinity }}
                initial={{ y: 0 }}
                animate={{ y: -innerHeight }}
            >
                <li use:motion>
                    <img {src} alt="image" class="rounded" />
                </li>
            </Motion>
        {/each}
    {/each}
</ul>

Essentially you have two stacks, they go in a loop from top to bottom (you can mess with direction, rate, etc). Once it gets to the end it loops back around. you have 2 stacks so once it gets to the bottom it looks seamless as it loops. Any questions feel free to ask. if you need it in React let me know. Hope this helps

like image 78
Bobby Mannino Avatar answered Dec 08 '25 21:12

Bobby Mannino