elementor4fun-logo
Last update: October 13, 2022

A better Smooth Scroll with Lenis

Lenis is a very light and easy to use Smooth Scrolling library. 

Step 1 - Install the lib

In a Code Block (or you can use a Snippet Manager if you prefer), add the following line in the PHP panel:

<script src="https://cdn.jsdelivr.net/gh/studio-freight/lenis@latest/bundled/lenis.js"></script>

Step 2 - Add the JS

In the same code block, paste this code in the Javascript panel :

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

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

requestAnimationFrame(raf);

And that's basically it...Couldn't be easier ;)

This current page actually uses this Smooth Scroll library.

How to deal with anchor links

If you also want to have a smooth scroll effect when you click on some anchor links, you need to use the onclick attribute:

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

With Oxygen, we simply need to add a new Attribute (advanced tab) and add lenis.scrollTo('#top') for the value:

Note that you will see an error : "Value may NOT contain quotes..." when pasting or writing the value. That's normal, you can ignore it, it will still work as expected.

The scrollTo method has some options, so you can set an offset, change the duration or even change the easing effect.

Example: lenis.scrollTo('#top',{offset:100,duration:4})

More info in the official page : https://github.com/studio-freight/lenis

closealign-justifyarrow-upchevron-downcaret-up