Search code examples
javascripthtmlscrollmouseeventsmooth-scrolling

Javascipt smooth scrolling experience


For days and days I have been trying to recreate the smooth scrolling of this page :

http://thibaudallie.com/

and without success. I see this kind of effect everywhere on awwwards but I have never found the right solution.

It's the best track I have right now, but I don't think it's the right one ...

I would like something that is triggered during the : " wheel ".

<script>
        const body = document.body,
            scrollWrap = document.getElementsByClassName("smooth-scroll-wrapper")[0],
            height = scrollWrap.getBoundingClientRect().height - 1,
            speed = 0.04;

        let offset = 0;

        body.style.height = Math.floor(height) + "px";

        function smoothScroll() {
            offset += (window.pageYOffset - offset) * speed;

            let scroll = `translate3d(0px, ${offset * -1}px, 0)`;
            scrollWrap.style.transform = scroll;

            callScroll = requestAnimationFrame(smoothScroll);
        }

        smoothScroll();
    </script>

Solution

  • I've found this in codepen Smooth Page Scroll

    var html = document.documentElement;
    var body = document.body;
    
    var scroller = {
        target: document.querySelector("#scroll-container"),
        ease: 0.05, // <= scroll speed
        endY: 0,
        y: 0,
        resizeRequest: 1,
        scrollRequest: 0,
    };
    
    var requestId = null;
    
    TweenLite.set(scroller.target, {
        rotation: 0.01,
        force3D: true
    });
    
    window.addEventListener("load", onLoad);
    
    function onLoad() {    
        updateScroller();  
        window.focus();
        window.addEventListener("resize", onResize);
        document.addEventListener("scroll", onScroll); 
    }
    
    function updateScroller() {
    
        var resized = scroller.resizeRequest > 0;
    
        if (resized) {    
            var height = scroller.target.clientHeight;
            body.style.height = height + "px";
            scroller.resizeRequest = 0;
        }
    
        var scrollY = window.pageYOffset || html.scrollTop || body.scrollTop || 0;
    
        scroller.endY = scrollY;
        scroller.y += (scrollY - scroller.y) * scroller.ease;
    
        if (Math.abs(scrollY - scroller.y) < 0.05 || resized) {
            scroller.y = scrollY;
            scroller.scrollRequest = 0;
        }
    
        TweenLite.set(scroller.target, { 
            y: -scroller.y 
        });
    
        requestId = scroller.scrollRequest > 0 ? requestAnimationFrame(updateScroller) : null;
    }
    
    function onScroll() {
        scroller.scrollRequest++;
        if (!requestId) {
            requestId = requestAnimationFrame(updateScroller);
        }
    }
    
    function onResize() {
        scroller.resizeRequest++;
        if (!requestId) {
            requestId = requestAnimationFrame(updateScroller);
        }
    }