back to home

darkroomengineering / lenis

Smooth scroll at it should be

13,226 stars
522 forks
25 issues
TypeScriptAstroVue

AI Architecture Analysis

This repository is indexed by RepoMind. By analyzing darkroomengineering/lenis in our AI interface, you can instantly generate complete architecture diagrams, visualize control flows, and perform automated security audits across the entire codebase.

Our Agentic Context Augmented Generation (Agentic CAG) engine loads full source files into context, avoiding the fragmentation of traditional RAG systems. Ask questions about the architecture, dependencies, or specific features to see it in action.

Embed this Badge

Showcase RepoMind's analysis directly in your repository's README.

[![Analyzed by RepoMind](https://img.shields.io/badge/Analyzed%20by-RepoMind-4F46E5?style=for-the-badge)](https://repomind-ai.vercel.app/repo/darkroomengineering/lenis)
Preview:Analyzed by RepoMind

Repository Summary (README)

Preview

LENIS

npm downloads size

Introduction

Lenis ("smooth" in latin) is a lightweight, robust, and performant smooth scroll library. It's designed by @darkroom.engineering to be simple to use and easy to integrate into your projects. It's built with performance in mind and is optimized for modern browsers. It's perfect for creating smooth scrolling experiences on your website such as WebGL scroll syncing, parallax effects, and much more, see Demo and Showcase.

Read our Manifesto to learn more about the inspiration behind Lenis.

<br/> <br/>

Sponsors

If you’ve used Lenis and it made your site feel just a little more alive, consider sponsoring.

Your support helps us smooth out the internet one library at a time—and lets us keep building tools that care about the details most folks overlook.

<!-- sponsors -->

syntaxfm ae-com smsunarto thearkis cachet-studio ironvelvet mariosmaselli vallafederico bizarro mielucristian itsoffbrand glauber-sampaio velox-themes blackpixelca Tarang74 joevingracien

<!-- sponsors --> <br/> <br/> <a href="https://vercel.com/oss"> <img alt="Vercel OSS Program" src="https://vercel.com/oss/program-badge.svg" /> </a> <br/>

Packages

<br/>

Installation

Using a package manager:

npm i lenis
# or
yarn add lenis
# or
pnpm add lenis
import Lenis from 'lenis'
<br/>

Using scripts:

<script src="https://unpkg.com/lenis@1.3.17/dist/lenis.min.js"></script> 
<br/>

Setup

Basic:

// Initialize Lenis
const lenis = new Lenis({
  autoRaf: true,
});

// Listen for the scroll event and log the event data
lenis.on('scroll', (e) => {
  console.log(e);
});

Custom raf loop:

// Initialize Lenis
const lenis = new Lenis();

// Use requestAnimationFrame to continuously update the scroll
function raf(time) {
  lenis.raf(time);
  requestAnimationFrame(raf);
}

requestAnimationFrame(raf);

Recommended CSS:

Import stylesheet:

import 'lenis/dist/lenis.css'

Or link the CSS file:

<link rel="stylesheet" href="https://unpkg.com/lenis@1.3.17/dist/lenis.css">

Or add it manually:

See lenis.css stylesheet

GSAP ScrollTrigger:

// Initialize a new Lenis instance for smooth scrolling
const lenis = new Lenis();

// Synchronize Lenis scrolling with GSAP's ScrollTrigger plugin
lenis.on('scroll', ScrollTrigger.update);

// Add Lenis's requestAnimationFrame (raf) method to GSAP's ticker
// This ensures Lenis's smooth scroll animation updates on each GSAP tick
gsap.ticker.add((time) => {
  lenis.raf(time * 1000); // Convert time from seconds to milliseconds
});

// Disable lag smoothing in GSAP to prevent any delay in scroll animations
gsap.ticker.lagSmoothing(0);

React:

See documentation for lenis/react.

<br/>

Settings

OptionTypeDefaultDescription
wrapperHTMLElement, WindowwindowThe element that will be used as the scroll container.
contentHTMLElementdocument.documentElementThe element that contains the content that will be scrolled, usually wrapper's direct child.
eventsTargetHTMLElement, WindowwrapperThe element that will listen to wheel and touch events.
smoothWheelbooleantrueSmooth the scroll initiated by wheel events.
lerpnumber0.1Linear interpolation (lerp) intensity (between 0 and 1).
durationnumber1.2The duration of scroll animation (in seconds). Useless if lerp defined.
easingfunction(t) => Math.min(1, 1.001 - Math.pow(2, -10 * t))The easing function to use for the scroll animation, our default is custom but you can pick one from Easings.net. Useless if lerp defined.
orientationstringverticalThe orientation of the scrolling. Can be vertical or horizontal.
gestureOrientationstringverticalThe orientation of the gestures. Can be vertical, horizontal or both.
syncTouchbooleanfalseMimic touch device scroll while allowing scroll sync (can be unstable on iOS<16).
syncTouchLerpnumber0.075Lerp applied during syncTouch inertia.
touchInertiaExponentnumber1.7Manage the strength of syncTouch inertia.
wheelMultipliernumber1The multiplier to use for mouse wheel events.
touchMultipliernumber1The multiplier to use for touch events.
infinitebooleanfalseEnable infinite scrolling! syncTouch: true is required on touch devices (See example).
autoResizebooleantrueResize instance automatically based on ResizeObserver. If false you must resize manually using .resize().
preventfunctionundefinedManually prevent scroll to be smoothed based on elements traversed by events. If true is returned, it will prevent the scroll to be smoothed. Example: (node) => node.classList.contains('cookie-modal').
virtualScrollfunctionundefinedManually modify the events before they get consumed. If false is returned, the scroll will not be smoothed. Examples: (e) => { e.deltaY /= 2 } (to slow down vertical scroll) or ({ event }) => !event.shiftKey (to prevent scroll to be smoothed if shift key is pressed).
overscrollbooleantrueSimilar to CSS overscroll-behavior (https://developer.mozilla.org/en-US/docs/Web/CSS/overscroll-behavior).
autoRafbooleanfalseWhether or not to automatically run requestAnimationFrame loop.
anchorsboolean, ScrollToOptionsfalseScroll to anchor links when clicked. If true is passed, it will enable anchor links with default options. If ScrollToOptions is passed, it will enable anchor links with the given options.
autoTogglebooleanfalseAutomatically start or stop the lenis instance based on the wrapper's overflow property, ⚠️ this requires Lenis recommended CSS. Safari > 17.3, Chrome > 116 and Firefox > 128 (https://caniuse.com/?search=transition-behavior).
allowNestedScrollbooleanfalseAllow nested scrolls. If true is passed, it will allow nested scrolls. If false is passed, it will not allow nested scrolls. ⚠️ To be used with caution since this can lead to performance issues, prefer using prevent or data-lenis-prevent instead.
naiveDimensionsbooleanfalseIf true, Lenis will use naive dimensions calculation. ⚠️ Be careful, this has a performance impact.
stopInertiaOnNavigatebooleanfalseIf true, Lenis will stop inertia when an internal link is clicked.
<br/> <!-- `target`: goal to reach - `number`: value to scroll in pixels - `string`: CSS selector or keyword (`top`, `left`, `start`, `bottom`, `right`, `end`) - `HTMLElement`: DOM element <br/> `options`: - `offset`(`number`): equivalent to [`scroll-padding-top`](https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-padding-top) - `lerp`(`number`): animation lerp intensity - `duration`(`number`): animation duration (in seconds) - `easing`(`function`): animation easing - `immediate`(`boolean`): ignore duration, easing and lerp - `lock`(`boolean`): whether or not to prevent user from scrolling until target reached - `onComplete`(`function`): called when target is reached -->

Properties

PropertyTypeDescription
animatedScrollnumberCurrent scroll value
dimensionsobjectDimensions instance
directionnumber1: scrolling up, -1: scrolling down
emitterobjectEmitter instance
optionsobjectInstance options
targetScrollnumberTarget scroll value
timenumberTime elapsed since instance creation
actualScrollnumberCurrent scroll value registered by the browser
lastVelocitynumberlast scroll velocity
velocitynumberCurrent scroll velocity
isHorizontal (getter)booleanWhether or not the instance is horizontal
isScrolling (getter)boolean, stringWhether or not the scroll is being animated, smooth, native or false
isStopped (getter)booleanWhether or not the user should be able to scroll
limit (getter)numberMaximum scroll value
progress (getter)numberScroll progress from 0 to 1
rootElement (getter)HTMLElementElement on which Lenis is instanced
scroll (getter)numberCurrent scroll value (handles infinite scroll if activated)
className (getter)stringrootElement className
<br/>

Methods

MethodDescriptionArguments
raf(time)Must be called every frame for internal usage.time: in ms
scrollTo(target, options)Scroll to target.target: goal to reach<ul><li>number: value to scroll in pixels</li><li>string: CSS selector or keyword (top, left, start, bottom, right, end)</li><li>HTMLElement: DOM element</li></ul>options<ul><li>offset(number): equivalent to scroll-padding-top</li><li>lerp(number): animation lerp intensity</li><li>duration(number): animation duration (in seconds)</li><li>easing(function): animation easing</li><li>immediate(boolean): ignore duration, easing and lerp</li><li>lock(boolean): whether or not to prevent the user from scrolling until the target is reached</li><li>force(boolean): reach target even if instance is stopped</li><li>onComplete(function): called when the target is reached</li><li>userData(object): this object will be forwarded through scroll events</li></ul>
on(id, function)id can be any of the following instance events to listen.
stop()Pauses the scroll
start()Resumes the scroll
resize()Compute internal sizes, it has to be used if autoResize option is false.
destroy()Destroys the instance and removes all events.

Events

EventCallback Arguments
scrollLenis instance
virtual-scroll{deltaX, deltaY, event}
<br/>

Considerations

Nested scroll

Using Javascript

<div id="modal">scrollable content</div>
const lenis = new Lenis({
  prevent: (node) => node.id === 'modal',
})

See example

Using HTML

<div data-lenis-prevent>scrollable content</div>

See example

Prevent wheel events only:

<div data-lenis-prevent-wheel>scrollable content</div>

Prevent touch events only:

<div data-lenis-prevent-touch>scrollable content</div>

Anchor links

By default, Lenis will prevent anchor links from working while scrolling. To enable them, you must set anchors: true.

new Lenis({
  anchors: true
})

You can also use scrollTo options:

new Lenis({
  anchors: {
    offset: 100,
    onComplete: ()=>{
      console.log('scrolled to anchor')
    }
  }
})
<br/>

Limitations

  • no support for CSS scroll-snap, you must use (lenis/snap)
  • capped to 60fps on Safari (source) and 30fps on low power mode
  • smooth scroll will stop working over iframe since they don't forward wheel events
  • position fixed seems to lag on MacOS Safari pre-M1 (source)
  • touch events may behave unexpectedly when syncTouch is enabled on iOS < 16
  • nested scroll containers require proper configuration to work correctly
<br/>

Troubleshooting

  • Make sure you use the latest version of Lenis
  • Include the recommended CSS
  • If using GSAP ScrollTrigger, ensure proper integration (see GSAP ScrollTrigger setup section)
  • Test without Lenis to ensure your element/page is scrollable
  • Be sure to use autoRaf: true or manually call lenis.raf(time) in your animation loop
<br/>

Tutorials

<br/>

Plugins

<br/>

License

MIT © darkroom.engineering