Giter VIP home page Giter VIP logo

lenis's Introduction

LENIS

npm downloads size

Introduction

Lenis 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 synching, parallax effects and much more. See Demo and Showcase.


Sponsorship

If you like Lenis, please consider sponsoring us. Your support helps us maintain the project and continue to improve it.


Packages


Installation

JavaScript

using a package manager:

npm i lenis
import Lenis from 'lenis'

using scripts:

<script src="https://unpkg.com/[email protected]/dist/lenis.min.js"></script> 

Setup

Basic:

const lenis = new Lenis()

lenis.on('scroll', (e) => {
  console.log(e)
})

function raf(time) {
  lenis.raf(time)
  requestAnimationFrame(raf)
}

requestAnimationFrame(raf)

Recommended CSS:

html.lenis, html.lenis body {
  height: auto;
}

.lenis.lenis-smooth {
  scroll-behavior: auto !important;
}

.lenis.lenis-smooth [data-lenis-prevent] {
  overscroll-behavior: contain;
}

.lenis.lenis-stopped {
  overflow: hidden;
}

.lenis.lenis-smooth iframe {
  pointer-events: none;
}

or link the CSS file:

<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/lenis.css">

or import it:

import 'lenis/dist/lenis.css'

GSAP ScrollTrigger:

const lenis = new Lenis()

lenis.on('scroll', (e) => {
  console.log(e)
})

lenis.on('scroll', ScrollTrigger.update)

gsap.ticker.add((time)=>{
  lenis.raf(time * 1000)
})

gsap.ticker.lagSmoothing(0)

React:

See documentation for lenis/react.


Instance settings

Option Type Default Description
wrapper HTMLElement, Window window The element that will be used as the scroll container
content HTMLElement document.documentElement The element that contains the content that will be scrolled, usually wrapper's direct child
eventsTarget HTMLElement, Window wrapper The element that will listen to wheel and touch events
smoothWheel boolean true Smooth the scroll initiated by wheel events
lerp number 0.1 Linear interpolation (lerp) intensity (between 0 and 1)
duration number 1.2 The duration of scroll animation (in seconds). Useless if lerp defined
easing function (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
orientation string vertical The orientation of the scrolling. Can be vertical or horizontal
gestureOrientation string vertical The orientation of the gestures. Can be vertical, horizontal or both
syncTouch boolean false Mimic touch device scroll while allowing scroll sync (can be unstable on iOS<16)
syncTouchLerp number 0.075 Lerp applied during syncTouch inertia
touchInertiaMultiplier number 35 Manage the the strength of syncTouch inertia
wheelMultiplier number 1 The multiplier to use for mouse wheel events
touchMultiplier number 1 The multiplier to use for touch events
infinite boolean false Enable infinite scrolling! syncTouch: true is required on touch devices. (See example)
autoResize boolean true Resize instance automatically based on ResizeObserver. If false you must resize manually using .resize()
prevent function undefined Manually 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')
virtualScroll function undefined Manually 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)

Instance Props

Property Type Description
animatedScroll number Current scroll value
dimensions object Dimensions instance
direction number 1: scrolling up, -1: scrolling down
emitter object Emitter instance
options object Instance options
targetScroll number Target scroll value
time number Time elapsed since instance creation
actualScroll number Current scroll value registered by the browser
lastVelocity number last scroll velocity
velocity number Current scroll velocity
isHorizontal (getter) boolean Whether or not the instance is horizontal
isScrolling (getter) boolean, string Whether or not the scroll is being animated, smooth, native or false
isStopped (getter) boolean Whether or not the user should be able to scroll
limit (getter) number Maximum scroll value
progress (getter) number Scroll progress from 0 to 1
rootElement (getter) HTMLElement Element on which Lenis is instanced
scroll (getter) number Current scroll value (handles infinite scroll if activated)
className (getter) string rootElement className

Instance Methods

Method Description Arguments
raf(time) Must be called every frame for internal usage. time: in ms
scrollTo(target, options) Scroll to target. target: goal to reach
  • number: value to scroll in pixels
  • string: CSS selector or keyword (top, left, start, bottom, target): goal to reach
    • number: value to scroll in pixels
    • string: CSS selector or keyword (top, left, start, bottom, right, end)
    • HTMLElement: DOM element
    options
    • offset(number): equivalent to 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 the user from scrolling until the target is reached
    • force(boolean): reach target even if instance is stopped
    • onComplete(function): called when the target is reached
    • userData(object): this object will be forwarded through scroll events
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.

Instance Events

Event Callback Arguments
scroll Lenis instance
virtual-scroll {deltaX, deltaY, event}

Considerations

Nested scroll

Using Javascript

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

Using HTML

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

prevent wheel events only

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

prevent touch events only

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

See modal example

Anchor links

<a href="#anchor" onclick="lenis.scrollTo('#anchor')">scroll to anchor</a>

Limitations

  • no support for CSS scroll-snap (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)

Tutorials


Plugins


Lenis in use


Authors

This set of hooks is curated and maintained by the darkroom.engineering team:


License

The MIT License.

lenis's People

Contributors

arzafran avatar baptistebriel avatar clementroche avatar daniacu avatar dechowpen avatar dependabot[bot] avatar edoardolunardi avatar gabedahl avatar gfier avatar haroldao avatar henrygd avatar ixkaito avatar kyrregjerstad avatar lutymane avatar matiasperz avatar mattrothenberg avatar mickaelchanrion avatar zachkrall avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

lenis's Issues

Anchor links are jumping to target #element instead of scrolling smoothly

Hello,

Because I need to have scroll-behavior: initial it does what it does as default - scroll jump to the target element. So if I want to scroll to element smoothly, I need to catch the click events for anchors and use Lenis.scrollTo(...) to make scroll smooth.

My question is if there are plans to handle this all in Lenis - for example with some parameter (for example { .., smoothAnchors: boolean, ... }) when initializing Lenis instance.

NPM

Hello. I tried to install it and build with npm but I cant get a demo html. Please can you tell me what I do wrong? Best regards, Karl

Demo site is not loading

At the time of this issue being opened, the demo site won't load.

  • Google Chrome v105.0.5195.125 (also tried incognito)
  • MacOS 12.6

Screenshot 2022-09-28 at 15 36 10

Parallax!!!

Hi its not an issue but just an enquiry is there any inbuilt parallax available for this smooth scroll
thank you

Lenis.scrollTo() - Duration / easing not working properly?

First of all, thanks for the best smooth scrolling library out there! Being able to use position: sticky again is liberating.

I'm trying to setup some anchor links smooth scrolling using Lenis.scrollTo() function, but I'm not sure if I understand how duration and easing works. Here's my current code:

  const scrollButtons = document.querySelectorAll('.button-scroll');
  scrollButtons.forEach(button => {
    button.addEventListener('click', e => {
    	e.preventDefault();
    	var target = button.dataset.target;
      lenis.scrollTo(target, {
      	offset: 0, 
        immediate: false, 
        duration: 3,
        easing: (x) => (x < 0.5 ? 8 * x * x * x * x : 1 - pow(-2 * x + 2, 4) / 2)
      });
    });

The expectation here is to have the anchor link triggering a scroll with 3 seconds of duration, using a easeInOutQuart function for easing. However, the scroll happens extremely fast and the easing function is not applied.

Am I doing something wrong? Can you guys add more details about these properties on the documentation?

Scrollbar drag teleport issue

Describe the bug
When enabling lenis on 2 of my websites, I get an issue when trying to click the scroll bar and drag it up and down.

Screencast.from.24-11-2022.13.54.50.webm

To Reproduce
This code is used in my website, also CSS properties for the full height are set.

const lenis = new Lenis({
  duration: 1.2,
  easing: (t) => Math.min(1, 1 - Math.pow(2, -10 * t)),
  direction: 'vertical',
  gestureDirection: 'vertical',
  smooth: true,
  mouseMultiplier: 2,
  smoothTouch: false,
})

function raf(time) {
  lenis.raf(time)
  requestAnimationFrame(raf)
}

requestAnimationFrame(raf)

This does not happen with Locomotive scroll for example.
EDIT: Tested with opera 93 (page teleport) and chrome 107 (scroll completely locked)
Also same behaviour on Safari Mac

Nested scrolling inside div not working (React)

Hello,

I have used the package and declared lenis object as per documentation in App.js inside an useEffect hook.

useEffect(()=> {
	const lenis = new Lenis({
		lerp: 0.1,
		smooth: true,
	});
	const scrollFn = () => {
		lenis.raf();
		requestAnimationFrame(scrollFn);
	};
	requestAnimationFrame(scrollFn);
 },[])

Now in a page where I have to add a div container with scrolling content, just like in your demo website. I have added same overflow technique with fixed container and content height but its not working on mouseover like that in your demo. I have to click and hold on scroller thumb to scroll down content.

If I remove the lenis declaration from app.js, this container scroll works normally.

Demo:

https://codesandbox.io/embed/recursing-zeh-1z10dm?fontsize=14&hidenavigation=1&theme=dark

Update:

Issue is Fixed. I forgot to add onWheel function to container.

Thanks for simple and very effective package.

scrollTo immediate how to?

I'm strictly unable to scroll to an element without easing and duration, could you please provide an example?

Here is what I tried, without success :

lenis.scrollTo('.section--about--first', {immediate: true})
lenis.scrollTo('.section--about--first', {offset: 0, duration: 0, easing: (t) => Math.min(1, 1.001 - Math.pow(2, -10 * t)), immediate: true})

How does it need to be witten?

Thank you

Cant start Lenis

I installed using NPM and Webpack and when i try to start, i get this error in console:

Unexpected token (53:11) - You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file.

Is there any dependence i'm missing or am i installing it wrong?

cdn for Lenis

Good afternoon. Could you please tell me how to add Lenisenis to cdnjs.com ? Just my website is on Tilda builder and I can't install the library via npm

Documentation improvement

Hey guys !

Just wanting to submit an issue I had.

I figured out where was the problem :

When there is height: 100% set to html, body (I use it on all my projects), the lib is not working.

E.g :

html, body{
  width: 100%;
  height: 100%;
}

A codepen as a DEMO : https://codepen.io/haroldao/pen/OJvgrXy
Normal DEMO (where it's working) : https://codepen.io/haroldao/pen/PoRpqXv

The solution:
Instead of height: 100%, we should set a min-height (min-height: 100%).

E.g :

html, body{
  width: 100%;
  min-height: 100%;
}

Last tick of direction getter returns -1

Hello,
I noticed a strange behaviour on the direction getter when I scroll down.
It works perfectly except when it stops. His last tick returns -1 instead of 1.

Here's my code :

lenis.on('scroll', ({direction}) => {
  console.log(direction)
})

Here's a screenshot of my console
Capture d’écran 2022-11-23 à 11 44 30

Am I missing something ?
Thank you very much :)

Import via CDN

Can you provide a CDN URL so we can import without having to use npm etc.

Thank you for your work.

Can't get this running

Hi @studio,

./ path and folder problems in Visual Code, can't get this module running.
Are there other ways to import this .js ?

Thank you

Working demo

Is it possible to get a working demo from this repo? / Sylvia

NextJs example

First of all, thanks for the fantastic plugin.
I wonder if there's an example demonstrating how to correctly implement it in a NextJs project? I followed the doc's basic setup and put it inside a useEffect hook with a return func that destroys the instance on route change, but it seems like nothing works. Any pointers would be greatly appreciated!

here's my setup:

import Lenis from "@studio-freight/lenis";

export default function Home(){

  useEffect(() => {
    if (!lenis) return;
    const lenis = new Lenis({
      duration: 1.2,
      easing: (t) => (t === 1 ? 1 : 1 - Math.pow(2, -10 * t)), // https://easings.net
      smooth: true,
      direction: "vertical",
    });

    const scrollFn = () => {
      lenis.raf();
      requestAnimationFrame(scrollFn);
    };
    requestAnimationFrame(scrollFn);

    return () => {
      if (lenis) {
        lenis.destroy();
      }
    };
  }, []);
}

setScroll or scrollTo not changing scroll position if scrolling / having inertia

Describe the bug
Methods setScroll() or scrollTo() won't work due to inertia. If there is a call to one of these methods while scrolling (or having some inertia), it won't work. Or at least it will not reset the right scroll position.

To Reproduce
https://codepen.io/benjaminrobinet/pen/KKeymNV
I added a button on the bottom right of the screen that calls a lenis.setScroll(0). Just try to click it while having inertia: it won't change the scroll position.

Conflict with another scrolling behavior

Hi! Thanks so much for sharing this to the world, it has been very helpful for me.

I have a question, it is not an issue, however I can't fix it by myself.
I have another script on my page to disable scrolling when a modal is opened. With the Lenis script it doesn't work.
The script looks like this :

<script>
document.addEventListener('DOMContentLoaded', () => {
 document.querySelectorAll('.menu-wrapper').forEach(trigger => {
  trigger.addEventListener('click', function(){ 
    document.querySelectorAll('.body').forEach(target => target.classList.add('no-scroll')); 
    });
 });

 document.querySelectorAll('.menu-wrapper').forEach(trigger => {
  trigger.addEventListener('click', function(){ 
    this.x = ((this.x || 0) + 1)%2; 
    if(!this.x){ 
      document.querySelectorAll('.body').forEach(target => target.classList.remove('no-scroll'));
    } 
    });
 });
});
</script>

I think it would help if I could apply the Lenis script only to my .body class.
How can I achieve that ?
Would you have any other adivce to make this work ?

Thank you in advance !

Documentation

Hello, can't find anywhere more details on these 3 options:

  • smoothTouch: false
  • touchMultiplier: 2
  • inifinite: false

Can you explain them properly with examples? Thank you.

No support for keystrokes (up, down, spacebar)

Hi! First of all loved your presentation at awwwwards!

We are trying to implement Lenis for the first time but we are bumping into no support for keyboard...
Is this something on the roadmap? I guess it wouldn't be too hard to implement right?
Also nice from an accessibility point of view.

New site submission

I don't know how you keep track of sites that use Lenis, so I'm opening an issue 😄

Here's a brand-new one that I've developed, this time replacing GSAP's ScrollSmoother with Lenis: https://www.heights.agency/
I've added Lenis at an advanced state of the project, and everything went extremely smoothly.

Nice job everyone! 👏

Horizontal scroll

Hi Lenis team,
I'm not able to make horizontal scroll work. Is there something to keep in mind when implementing horizontal scroll?
I have a basic setup with a flex horizontal layout. If it's needed I can provide a codepen.

Spacebar is scrolling the page

I have Lenis throughout my website and when a user is typing info in the form, if they hit spacebar, the page scrolls down.

I tested it by removing the smooth scroll and it works. Is there a fix for this? Maybe how to block a section from having smooth scroll?

To see what is happening you can check here:
https://darren-voros.webflow.io/contact

Thank you!

v0.2.0 keeps sending endless scroll event, no scroll happening

Lenis version: 0.2.0
Browsers: All
OS: Windows

In v0.2.0, Lenis seem to have some kind of a problem, and keep sending endless scroll events, which causes scroll to not happen (as it keep trying to go back up to 0, I assume)

Minimal demo, try scrolling, both mousewheel and scrollbar, and check the console for the endless event being sent:
https://codepen.io/eldzej/pen/oNdXVgR

Been using 0.1.12 to great satisfaction after a ton of issues with LocomotiveScroll, so not sure what happen in v0.2.0

NaN if Lenis is created while wheel events are coming in

Hi guys, thanks for a great lib!

I noticed that reloading the page while wheel events (trackpad on a Macbook pro) are still coming in, the onscroll returns NaN as value and then scrolling breaks.

You can recreate by scrolling to top on the demo site and quickly reloading at the top:

Screenshot 2022-09-12 at 13 12 06

Issue with scrollTo + immediate

I'm having an issue doing the following for a page transition:

// Transition animation starts
lenis.stop()

// Transition covers up the page
lenis.scrollTo(0, { immediate: true })

// When the page transition ends after a short time, free the scroll again
lenis.start()

The problem

The problem is that if the user changes the page before the scroll animation reaches its target, the scroll remembers the last point before the scrollTo executes. So when I start it back again it animates from there to the top trying to reach the new target.

You can reproduce it in the following link by pressing the space right before the scroll animation ends.
https://codepen.io/matias4205/pen/MWXWQMa

Zoom-in/Zoom-out scrolls the page issue

Hello, I have been using this amazing and simple package for smooth scrolling on various projects. Thanks to all authors and contributors.

Now, problem is that normal zoom-in and zoom-out does not work. Like page does zooms in but it also scrolls the page up and down respectively.

For reference, you can check your own demo as well.

Question: any advice on how to use as plugin with Nuxt3

Hi,

Thank you for such a great library.

I was wondering if you could provide any advice on how to get it working as a plugin within a Nuxt3 project. The following is what I have so far for my plugin file lenis.client.js withing the plugins folder of the project

import Lenis from "@studio-freight/lenis";

const lenis = new Lenis({
  lerp: 0.1,
  smooth: true,
  direction: "vertical",
});

lenis.on("scroll", ({ scroll, limit }) => {
  console.log({ scroll, limit });
});

function raf() {
  lenis.raf();
  requestAnimationFrame(raf);
}

requestAnimationFrame(raf);

export default defineNuxtPlugin((nuxtApp) => {
  nuxtApp.provide("lenis", lenis);
});

Unfortunately the page stops scrolling and this is what I get on the console on scroll:

imagen

Thank you in advance for your help

Back swipe gesture not available

Hey I wanted to know if it's possible to enable browser touchpad swipe gesture in order to trigger back / next navigation ? It's caused by scroll-behavior: initial;

Lag in Chrome

I've tried Lenis on multiple sites and on all of them I experience a really bad lag. When I scroll it takes 2-3 secs before the script actually scrolls the page.

In the video below you can see when the numbers in the console update that's when I scroll with the mouse wheel, and pay attention after how many secs the page actually scrolls... here's a codepen with the code.

Untitled.mp4
  • Chrome: Version 103.0.5060.114 (Official Build) (arm64)
  • Brave: Version 1.41.96 Chromium: 103.0.5060.114 (Official Build)

Can't debug Lenis when returning NaN

Scroll is returning: {scroll: NaN, limit: 0, velocity: NaN, direction: -1, progress: NaN}

I have no idea, why this isn't working and with no way to debug install works perfectly with scrollSmoother and Locomotive scroll.

Javascript looks like this, set up is really simple. While it is a WP install I have a wrapper and content div that goes around the main html tag, super simple stuff.

Really confused why limit is not assigned, looking at other issues I can see the wheel event called before this can affect the scroll, however I have deleted all other references.

FYI the page does not move at all, any help on debugging this would be great.

` createScroll() {
this.scrollWrapper = document.querySelector('#smooth-wrapper')
this.scrollContent = document.querySelector('#smooth-content')

this.Scroll = new Lenis({
  duration: 1.2,
  wrapper: this.scrollWrapper,
  content: this.scrollContent,
  direction: 'vertical',
  smooth: true,
})

this.Scroll.on('scroll', ({ scroll, limit, velocity, direction, progress }) => {
  console.log({ scroll, limit, velocity, direction, progress })
})

const raf = () => {
  this.Scroll.raf()
  requestAnimationFrame(raf)
}

requestAnimationFrame(raf)

}`

Screenshot 2022-12-01 at 12 10 33

velocity overshoots zero

Hey! We noticed the velocity is a bit glitchy when the scroll momentum is about to come to a stop.

The velocity overshoots 0 briefly and switches sign which creates visual glitches when using to animate.

Typescript - EventEmitter class extension missing

Describe the bug
Currently the types are getting generated without the class extension from tiny-emitter causing typescript to error.

lenis.on('scroll', handleScroll); // Property 'on' does not exist on type 'Lenis'.

Current type output:

export default class Lenis {}

Expected type output (matches implementation):

export default class Lenis extends EventEmitter {}

I've tried solving this myself however I'm not very familiar with JSDoc syntax and couldn't get @typedef {import('tiny-emitter')} EventEmitter to play nicely with @extends EventEmitter.

If it would help I'd be happy to spend the time to migrate it directly to typescript, I didn't want to spend the time without any input from yourselves first.

Feature request: Custom Scrollbar

Hi Studio Freight team,
Nice library, very useful, and game changer for smooth scrolling, thank you to make this beautiful library.
I wonder if we can have a custom scrollbar (because Windows have suck scroll style and ruined the website UI).

What I mean by custom scrollbar is adding new div instead styling -webkit scroll on CSS (because it has limited styling, and depends on browser).
I understand we can make our own by using lenis.on('scroll') function, but it would be great if we have option like example customScroll: true, and automatically create custom div for scrollbar.

Like example Studio Freight projects:

Thank you.

Scroll is not smooth while using a large iframe

Hello,
I'm having trouble with one of my pages consisting of a 400px hero section, an iframe of this magnitude: height: 1547px; width: 1432px; and then my footer, while using Lenis. The height and width of the iframe are loaded right before Lenis is initialized. What is it I might be doing wrong?
Thanks in advance.

Scroll callback "direction" output suggestion

Hi!

After using the scroll callback, I've been wondering if the returned direction parameter should output the direction of the user's scroll input instead of the global instance direction.

Current behavior

import Lenis from '@studio-freight/lenis'

const lenis = new Lenis({
  	direction: 'vertical', 
  	smooth: true,
})

lenis.on('scroll', ({ direction }) => {
  	console.log({direction}); // In that case, it'll always return `vertical` (lenis.direction)
})

Suggested behavior

import Lenis from '@studio-freight/lenis'

const lenis = new Lenis({
  	direction: 'vertical', 
	smooth: true,
})

lenis.on('scroll', ({ direction }) => {
  console.log({direction}); // returns `1` or `-1`. Based on user scroll event
})

Would return 1 or -1 depending if the user is scrolling up and down (vertical) or left and right (horizontal).

I think this solution would make more sense since all other properties of that event are related to a scroll action, not the global instance.

Workaround

I've found a workaround to reproduce the suggested behavior. But I would like to know your thoughts on having this behavior built-in the library!

import Lenis from '@studio-freight/lenis'

let scrollDirection = 1
let lastProgress = 0

const lenis = new Lenis({
	direction: 'vertical', 
 	smooth: true,
})

lenis.on('scroll', ({ progress }) => {
	//get direction
	if (progress > lastProgress) {
		if (scrollDirection != 1) {
			scrollDirection = 1;
		}
	} else {
		if (scrollDirection != -1) {
			scrollDirection = -1;
		}
	}
})

reload from to top?

How do I do it when I reload doesn't save the scroll position, I want to start from the beginning/top

Lenis uses `Event.path` which is deprecated

Describe the bug
Not necessarily a bug and this is minor but I believe it would be good to use Event.composedPath() as Event.path is deprecated, as the Issues tab on the Chrome Tools notices so.

image

To Reproduce
Just use Lenis, Chrome returns this error:

Event.path is deprecated and will be removed. Please use Event.composedPath() instead.
1 source: @studio-freight_lenis.js:249

Should we have some debouncing?

I'm using this with r3f and I noticed 200+ console logs a second when I do something like lenis.on('scroll', (scroll)=>{console.log)). Should we limit it to like 30 a second?

How to use in Nuxt

Hi Mr Clementroche,

First of all thank you for this great smooth scroll which is open source really appreciated i have a question
How do i use in nuxt, i tried but when route change the scroll position is didn't go top it stick to the same position as the previous page.
hope you understand my problem please guide me on this thank you.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.