Search code examples
javascriptscrolljs-scrollby

Scroll down X pixels slowly in Java Script


I'm trying to make something in HTML for school that scrolls down to the next section when the down arrow is pressed.

Currently, the site scrolls down the number of pixels outputted by ((window.innerHeight+(window.innerHeight*0.1))+1).

Here is my Java Script code:

document.onkeydown = checkKey;
function checkKey(e) {
  e = e || window.event;
  if (e.keyCode == '40') {
    document.getElementById("mainbody").scrollBy({
      top: ((window.innerHeight+(window.innerHeight*0.1))+1),
      behavior: 'smooth'
    });
  }
}

The code makes scrolls down way too fast. Is there some way to scroll down slowly the same number of pixels in pure Java Script?

Thanks for any ideas.


Solution

  • // elementY: is the vertical offset of the whole page
    // duration: how long do you want the scroll last
    // for example: doScrolling(0, 300) will scroll to the very beginning of page
    // in 300ms
    function doScrolling(elementY, duration) {
      const startingY = window.pageYOffset
      const diff = elementY - startingY
      let start
    
      // Bootstrap our animation - it will get called right before next frame shall be rendered.
      window.requestAnimationFrame(function step(timestamp) {
        if (!start) start = timestamp
        // Elapsed milliseconds since start of scrolling.
        const time = timestamp - start
        // Get percent of completion in range [0, 1].
        const percent = Math.min(time / duration, 1)
    
        window.scrollTo(0, startingY + diff * percent)
    
        // Proceed with animation as long as we wanted it to.
        if (time < duration) {
          window.requestAnimationFrame(step)
        }
      })
    }