Image Slide in by scroll

Article

Image Slide in by scroll

Hi guys!
Today I'll show you a codepen that a images are sliding in from right side of the viewport as you scroll. This effect is created using Lenis and vanilla JavaScript. :)
Here is the codepen. (I recommend viewing it at 0.5x)



As always, I highlight only the important points to implement this scroll animation.
We have a function called isInViewport(). This function triggers the text animation and sliding images.

function isInViewport(element) {
    const rect = element.getBoundingClientRect()
    const windowHeight = window.innerHeight || document.documentElement.clientHeight
    const triggerHeight = windowHeight * 0.4
    return (
        rect.top >= -triggerHeight &&
        rect.bottom <= (windowHeight + triggerHeight)
    );
}


Since we use Lenis, we pack all that animations inside of the Lenis scroll event like below.

let lenisScroll;
lenis.on('scroll', (scroll) => {
    lenisScroll = scroll.animatedScroll

    imgWrapper.forEach(el => {
        if (isInViewport(el)) {
            let img = el.querySelector('img')
            const rect = img.getBoundingClientRect();
            const targetTop = rect.top + lenisScroll;

            const centerY = targetTop - 400;
            let translateAmount = (centerY - lenisScroll - window.innerHeight / 2)
            let rotateAmount = - (centerY - lenisScroll - window.innerHeight / 2)

            img.style.transform = `translate3d(-${0 + translateAmount * -0.35}%, -50%, 0) rotate(${-10 + (rotateAmount * 0.03)}deg)`;
        }
    });

    about.forEach(e => {
        if (isInViewport(e)) {
            e.classList.add('view')
        }
    });
})

lenisScroll updates the scroll position every time you scroll.

Each image has a parent element with the class name .imgWrapper, and if it's in the viewport, translate3d and rotate transforms are applied based on the element's position relative to the scroll.

That's all actually! ✨ It's not so complicated, isn't it??

Hope you enjoyed!

See you soon!

Categories