Search code examples
javascriptscroll

How to create smooth movement while mouse scrolling?


Normally mouse scroll, while scrolling, is "jumping". Through it, animations that depends from scrolling, looks nasty. I would like to create smooth page scrolling, like on this site: https://www.gv.com/

I'm not talking about scrolling to anchor after click, I'm talking about scrolling page to down and up, with mouse scroll.

How can I achieve that?


Solution

  • First step is to define the problem. We want the scrolling to slowdown a few pixels after we stopped scrolling with mouse. This should achieve the smoothness effect. I found out the easiest way is to use a speed variable to hold the speed of the scrolling, then scroll by it while slowing down. Of course this happens instead of the default scroll behavior.

    Ideally, one could use an easing out function, but I found out that multiplying by a factor of 0.9 is easier.

    Note: this implementation is buggy, but it's a first step :-)

    var speed = 0;
    var lastUpdateTime = 0;
    
    // must be active (not passive)
    addEventListener('wheel', function(ev) {
      speed = ev.deltaY;
      ev.preventDefault();
    }, {  passive: false })
    
    // a bad usage of the gameLoop...
    function update(deltaTime) {
      const easingFactor = 0.9;
      speed *= easingFactor;
    }
    
    // this probably rounds the speed...
    function render() {
      window.scrollBy(0, speed)
    }
    
    function gameLoop(currentTime) {
      const deltaTime = currentTime - lastUpdateTime;
      update(deltaTime);
      render();
      lastUpdateTime = currentTime;
      requestAnimationFrame(gameLoop);
    }
    
    
    requestAnimationFrame(gameLoop);
    .main {
      width: 300px;
      height: 4000px;
      background-color: green;
      background-image: url(https://picsum.photos/300/2000);
    }
    <div class="main">
      <h1>hello world</h1>
      <p>please scroll with mouse wheel</p>
    </div>