I am trying to use framer motion to animate a image sliding carousel. I want the animation to only start when I press a button. The problem is that the animation starts before I even click on the button. I have my 5 images in an array. Upon my button click, the animation should be as so: the first image should shrink and fade out into the background while the remaining four image should all slide towards the left.
the subsequent animation should be: now that the first image has disappeared, the second image should shrink and fade out into the background while the remaining 3 images should all slide towards the left.
and so on and so forth until only the last image is visible, the animation should stop there.
<div className="flex flex-col w-1/2 mt-32 ml-10">
<div
className="flex flex-row gap-10 overflow-x-scroll no-scrollbar scroll-smooth mx-5"
ref={containerRef}
>
{images.map((image, index) => (
<motion.img
key={index}
src={image}
alt={`Image ${index + 1}`}
initial={{ x: "+100%" }}
animate={{
opacity: index < currentIndex ? 0 : 1,
scale: index < currentIndex ? 0 : 1,
x: buttonClicked && index === currentIndex ? 0 : "-100%",
}}
transition={{ duration: 0.75 }}
/>
))}
</div>
<div className="flex flex-row mt-10 gap-12">
<button
className="flex bg-rose_ebony rounded-full w-[68px] h-[68px] items-center justify-center"
onClick={() => {
prevImage();
}}
disabled={currentIndex === 0}
>
<img src={arrow} className="" />
</button>
<button
className="flex bg-rose_ebony rounded-full w-[68px] h-[68px] items-center justify-center"
onClick={() => {
nextImage();
}}
disabled={currentIndex === images.length - 1}
>
<img src={arrow} className="rotate-180" />
</button>
</div>
</div>
so the animation for the opacity and scale works correctly. but the x axis animation is broken. the images automatically slide to the left the moment my page loads. I want it to only slide when I click on the button.
The moment your piece of code loads, the animation starts. The buttons have no influence on that.
If you want the animation to run only after a button-click, then load a new component on button-click. And that new component is animated.
The same for the next images: Load them in a small separate component and load that component on a button-click.