Create Beautiful Scroll Animations in Next.js Using Framer Motion

Create Beautiful Scroll Animations in Next.js Using Framer Motion

Introduction

Scrolling is something we do every day on our screens, but have you ever thought about how scrolling affects user experience? In today's world, scrolling has also become a way to give your users a smooth and satisfying experience. With tools like Framer Motion, developers can turn scrolling into an engaging and visually attractive experience.

Today, we will explore different ways to animate scrolling. We will learn about the types of scroll animations and how they are used. We’ll understand the pattern so that we can add scroll animations to any of our projects or sites.

We will create animations in Next.js using Framer Motion. If you prefer to use any other framework or library, you can use that.

So, without further delay, let’s get started.

Types of Scroll Animations

There are two types of scroll animations:

  1. Scroll-linked animations: Animations that move or change based on how far you’ve scrolled, the element will update continuously as you scroll.

  2. Scroll-triggered animations: A normal animation is triggered when an element enters or leaves the viewport.

With Framer motion, you can achieve both. Let’s understand both one by one.

Scroll-linked animations

Scroll-linked animations are animations where the progress or movement of an animation is directly linked up to how far the user has scrolled. In this type of animation, elements change continuously as the user scrolls.

It means if you are at point one then the animation will track you, and it will also be on point one. And, If you scroll and go to point two, the animation will follow you to that point.

Key Features

  • The animation is synchronized with the scroll progress.

  • As you scroll, the animation updates in real time based on how much you've scrolled.

  • These animations can involve moving, scaling, rotating, or changing the appearance of elements, usually using useScroll and useTransform hooks(we’ll learn about these ahead) in Framer Motion.

Scroll-triggered animation

Scroll-triggered animations happen when an element enters or leaves the specific viewport as you scroll. It means the animation starts only when the user scrolls to a specific part of the page.

So, if I am on point one and, I set a scroll-triggered animation for point three then this animation will occur at point three. This means that animation will triggered only when I reach that viewport(in this case it is point three)

To understand this, you can check this video👇. Here, you’ll see when that orange element comes in a viewport means it is completely visible on the screen and then, at that time, shows a navbar.

Key Features

  • Triggered by Scroll Position: The animation is activated once a specific scroll position is reached, rather than being continuously synced with the scroll, like scroll-linked animations. This is typically achieved using conditions like whileInView or onEnter.

  • Discrete Animations: Unlike scroll-linked animations, scroll-triggered animations happen at specific moments, like when an element enters or exits the viewport. These could include fade-ins, slide-ins, or other visual effects that occur once as the user scrolls past a certain point.

  • One-Time or Repeatable Animations: Scroll-triggered animations can be set to play only once when the element first comes into view, or they can repeat whenever the element enters the viewport again, depending on the use case.

      <motion.div
        initial="hidden"
        whileInView="visible"
        viewport={{ once: true }}  // animation will occur only once
      />
    

What’s Next?

Now we understand these two types of scroll animations and their differences, let's start understanding the patterns used in creating these animations. This will allow you to add scroll animations to any of your projects.

First, we'll set up a project to understand this practically, and then we will create both types of animations.

Project Setup

Let's start by setting up our Next.js project with all the necessary dependencies. I am going to use StalkBlitz for this project but you can use VSCode too. Although all the steps I’ll tell you from the VSCode perspective so you can follow the steps.

  1. Create a new Next.js project with TypeScript:

     npx create-next-app@latest
    

    On installation, you'll see the following prompts:

     What is your project named? my-app
     Would you like to use TypeScript? No / Yes
     Would you like to use ESLint? No / Yes
     Would you like to use Tailwind CSS? No / Yes
     Would you like to use `src/` directory? No / Yes
     Would you like to use App Router? (recommended) No / Yes
     Would you like to customize the default import alias (@/*)? No / Yes
     What import alias would you like configured? @/*
    
  2. Install Framer Motion

     npm install framer-motion
    
  3. Clean up default files.

    Remove the default code in app/page.tsx. We’ll start from scratch to focus on our scroll animations. The file should look like this.

     'use client';
    
     export default function Home() {
    
       return (
         <div>
    
         </div>
       );
     }
    
  4. Start the Development Server

     npm run dev
    

Create Scroll Animation

Now that our project is set up, we can create both types of scroll animations one by one. You can start writing code directly in app/page.tsx file or create a separate components and import all of them in app/page.tsx file.

Creating Scroll-Linked Animation

There are several examples of scroll-linked animation:

  • Scroll Progress Bar: A circular or linear progress bar that fills up as the user scrolls down the page.

  • Parallax Scrolling: Background images or elements move at different speeds relative to the foreground, creating a depth effect as you scroll.

  • Fade-In Elements: Content fades into view as the user scrolls.

  • Scale Transformations: Elements gradually increase or decrease in size based on scroll progress. etc.

Let’s create some animations. While creating any scroll-linked animation you'll frequently use these methods and hooks from framer motion.

  1. Scroll Progress Detection (useScroll): Tracks the user's scroll position, typically returning a value from 0 to 1 that represents the progress down the page.

     const { scrollYProgress } = useScroll();
    
  2. Transforming Scroll Data (useTransform): Maps the scroll position to specific animation properties like opacity, scale, or position. Use this to trigger animations like fading, moving, rotating, scaling, or color changes during the scroll.

     const scaleValue = useTransform(scrollYProgress, [0, 1], [1, 2]); // Example of scaling
     const opacityValue = useTransform(scrollYProgress, [0, 0.5, 1], [1, 0.5, 0]); // Example of fading out
    
  3. Animating with Motion Elements: Wrap target elements with motion.div (or any motion component) and link the animation to the scroll progress.

     <motion.div style={{ scale: scaleValue }}>Animated Content</motion.div>
    
  4. Transitions: Apply smooth transitions to make animations feel fluid and natural.

     <motion.div transition={{ duration: 0.8 }}>Smooth Transition</motion.div>
    
  5. Initial and Final States: Use initial, animate, or style props to define how elements look initially, and control their final states with useTransform or animations linked to scrollYProgress.

     <motion.div
       initial={{ opacity: 0, y: 50 }} // Starting state
       whileInView={{ opacity: 1, y: 0 }} // When the element comes into view
       transition={{ duration: 0.8 }}
     >
       Scroll to animate
     </motion.div>
    

Scroll Progress Bar

We'll start by creating a scroll progress bar. To do this, open your text editor, create a new component, and begin writing code in it.

import { motion, useScroll, useTransform } from 'framer-motion';

export default function ScrollProgress() {
  const { scrollYProgress } = useScroll();
  const progressValue = useTransform(scrollYProgress, [0, 1], [0, 1]);
  const strokeDasharray = useTransform(progressValue, [0, 1], [0, 283]);
  return (
    <div>
      <motion.svg
        className="fixed top-4 left-4"
        width="100"
        height="100"
        viewBox="0 0 100 100"
        fill="none"
        xmlns="http://www.w3.org/2000/svg"
      >
        <circle
          cx="50"
          cy="50"
          r="45"
          stroke="rgba(255,255,255,0.2)"
          strokeWidth="10"
        />
        <motion.circle
          cx="50"
          cy="50"
          r="45"
          stroke="#00FF00"
          strokeWidth="10"
          strokeDasharray="283"
          strokeDashoffset="0"
          style={{ strokeDashoffset: strokeDasharray }}
          initial={{ strokeDashoffset: 283 }}
          animate={{ strokeDashoffset: 0 }}
        />
      </motion.svg>
    </div>
  )
}

Here we use:

  • useScroll: Provides the scroll position as a normalized value between 0 and 1.

  • useTransform: Maps the scroll progress to the specific value ranges we need, whether it's for the stroke dasharray of the progress circle or any other transformation we want to apply.

  • motion Components: We use Framer Motion's motion.circle to animate the stroke length in real-time based on scrolling.

Dynamic Scaling Text Animation

In this example, we will create a scroll-linked dynamic scaling effect for a text element using Framer Motion.

  1. Tracking Scroll Progress: Similar to the progress bar, we use useScroll() to get the current scroll progress of the page. The scrollYProgress value ranges from 0 at the top to 1 when fully scrolled.

     const { scrollYProgress } = useScroll();
    
  2. Transforming the Scroll Value to Control Scale: We use useTransform() to convert the scroll progress into a scale value that changes dynamically as the user scrolls. In this case, we map the scrollYProgress from [0, 0.5, 1] to scale values [1, 2, 1], it means the text will grow from its original size, double in size at the middle of the scroll, and shrink back as you reach the bottom.

     const scaleValue = useTransform(scrollYProgress, [0, 0.5, 1], [1, 2, 1]);
    
  3. Animating the Text Element: Inside the motion.h1 component, we will use the scaleValue to the style property to smoothly animate the text scaling effect based on the scroll position. The text will "grow" and "shrink" as the user scrolls.

     <motion.h1
       style={{ scale: scaleValue }} // Applying the dynamic scale based on scroll
       className="text-6xl font-bold text-white drop-shadow-lg"
     >
       Scroll to Scale
     </motion.h1>
    
  4. Styling the Section: The text is centered within a full-screen section that has a background gradient to add visual appeal. The background creates a smooth gradient from purple to indigo, making the dynamic text stand out more.

     <div className="min-h-screen flex justify-center items-center bg-gradient-to-b from-purple-600 to-indigo-800">
    

Concepts Used:

  • useScroll: We use this hook again to track the page’s scroll progress, which serves as the trigger for the animation.

  • useTransform: Here, we map the scroll progress to scale values, making the text grow or shrink smoothly during the scroll event.

  • motion Components: The motion.h1 the component is animated in real-time, with the scale dynamically adjusted as the scroll value changes.

We again used the same concepts. useScroll useTransform and motion. So, this is the part of scroll-linked. Now let’s create some scroll-triggered animations.

Creating Scroll-Triggered Animation

Scroll-triggered animation doesn't stick to work with a few examples. You can link scroll animation to specific components of the page. For example, I have a landing page with two elements and a div containing some text. Currently, there are no animations on the page, but I want to add animations that activate when the viewport comes into view.

For this, we will use scroll-triggered animations. As we learned earlier, scroll-triggered animations occur when a particular viewport comes into view. So, let’s add Framer Motion elements to this code.

import { motion, useScroll, useTransform } from 'framer-motion';

export default function ScrollOne() {
  return (
    <section className="min-h-screen flex flex-col justify-center items-center bg-gradient-to-br from-pink-500 to-yellow-500 text-center">
    <motion.div
      initial={{ opacity: 0, y: 50 }}
      whileInView={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.8, ease: 'easeOut' }}
      className="p-8 bg-white/90 shadow-2xl rounded-3xl max-w-lg"
    >
      <h1 className="text-5xl font-extrabold text-transparent bg-clip-text bg-gradient-to-r from-blue-400 to-green-400 mb-6">
        Smooth Scroll Animation
      </h1>
      <p className="text-lg text-gray-700">
        This is a fade-in animation triggered by scrolling down. Enhance
        user experience by making content appear progressively as users
        scroll.
      </p>
    </motion.div>

    <motion.div
      initial={{ y: -100, opacity: 0 }}
      whileInView={{ y: 0, opacity: 1 }}
      transition={{ delay: 0.5, duration: 0.8 }}
      className="absolute top-[10%] text-2xl text-purple-200 font-semibold"
    >
      Top-to-Bottom Animated Text!
    </motion.div>
  </section>
  )
}
  1. We import motion from framer-motion

  2. The entire component is wrapped in a section element, it has some basic styling.

  3. The <motion.div> which is the first motion div. It contains the main content (a heading and paragraph). It uses initial and whileInView to create a scroll-triggered animation:

      • initial={{ opacity: 0, y: 50 }}: Initially, the box is invisible (opacity: 0) and positioned 50 pixels down (y: 50).

        * whileInView={{ opacity: 1, y: 0 }}: When the user scrolls it into view, it becomes fully visible (opacity: 1) and moves to its normal position (y: 0).

        * transition={{ duration: 0.8, ease: 'easeOut' }}: The transition takes 0.8 seconds and eases out smoothly.

    • The content inside is styled with Tailwind classes, giving it padding, a background with 90% opacity, shadow, rounded corners, and a max width.

  4. After that, we have a second motion div (Top-to-Bottom Animated Text). This <motion.div> animates some text that moves down from the top of the screen:

    • initial={{ y: -100, opacity: 0 }}: The text starts 100 pixels above its normal position and is invisible.

    • whileInView={{ y: 0, opacity: 1 }}: When it comes into view, it moves to its normal position and becomes fully visible.

    • transition={{ delay: 0.5, duration: 0.8 }}: There's a 0.5-second delay before the animation starts, giving a staggered effect.

The final output will look like this.

Conclusion

That’s it for today’s blog. We cover 2 types of animations with some methods used while creating these animations like: useScroll useTransition whileInView initial and final states and things like that.

All the code with more animation samples I have added in my StalkBliz project. You can check it out here and view more sample scroll animations with code. If you want to explore more props, methods, and examples of scroll animations, you can check out Framer Motion’s scroll docs here.

Thanks for reading this blog. If you learned something from it, please like and share it with your friends and community. I write blogs and share content on JavaScript, TypeScript, Open Source, and other web development-related topics. Feel free to follow me on my socials. I'll see you in the next one. Thank You :)

Did you find this article valuable?

Support Shivam Katare's Blog by becoming a sponsor. Any amount is appreciated!