Evan Gladstone
Evan Gladstone

Reputation: 127

How do I slow down the default speed of smooth scroll using only Javascript?

My goal is to press the enter key, and have the site scroll to the bottom. I have set the scroll behavior to smooth and everything works like it should, except the default speed of smooth scrolling is way too fast. How do I slow it down? Below is my code. No jquery please. Thank you!

 document.body.onkeyup = function(e){
     if(e.keyCode == 13){
          window.scrollBy(0, window.innerHeight * 8);
     }
 };

Upvotes: 3

Views: 8734

Answers (2)

Vala Khosravi
Vala Khosravi

Reputation: 2570

Here is my idea about slowing down the scroll action:

const breaks = 4;
const duration = 1600;
for (let i = 0; i <= breaks; i++) {
  setTimeout(
    () => {
      window.scrollTo({
        top: (thresold / breaks) * i,
        behavior: 'smooth',
      });
    },
    (duration / breaks) * i
  );
}

You can modify the behavior by changing breaks and duration.

Upvotes: 0

Carlos S&#225;
Carlos S&#225;

Reputation: 622

You can't change the default scrolling speed.

What you can do is create your own scrolling function (with no jQuery)!

function scrollBy(element, value, duration, easingFunc) {
  var startTime;
  var startPos = element.scrollTop;
  var clientHeight = element.clientHeight;
  var maxScroll = element.scrollHeight - clientHeight;
  var scrollIntendedDestination = startPos + value;
  // low and high bounds for possible scroll destinations
  var scrollEndValue = Math.min(Math.max(scrollIntendedDestination, 0), maxScroll)
  // create recursive function to call every frame
  var scroll = function(timestamp) {
    startTime = startTime || timestamp;
    var elapsed = timestamp - startTime;
    element.scrollTop = startPos + (scrollEndValue - startPos) * easingFunc(elapsed / duration);
    elapsed <= duration && window.requestAnimationFrame(scroll);
  };
  // call recursive function
  if (startPos != scrollEndValue) window.requestAnimationFrame(scroll);
}

var containerEl = document.getElementById("scroll-container");
var scrollingDistance = window.innerHeight * 3;
var scrollingTime = 1000;
var easeInOutCubic = function(t) {
  return t < .5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1;
}

scrollBy(containerEl , scrollingDistance , scrollingTime , easeInOutCubic )
html ,body, #scroll-container {height: 100vh; margin:0;}
#scroll-container {overflow-y: scroll;position:relative; }
section {height: 100%; display:block; position:relative; border-top: 1px solid black;}
<div id="scroll-container">
  <section id="page1">
    page1
  </section>
  <section id="page2">
    page2
  </section>
  <section id="page3">
    page3
  </section>
  <section id="page4">
    page4
  </section>
</div>

With this you can specify the time you want the scrolling to take.

In the example I use 1000ms but you can set that to anything you want, or set it based on the amount to scroll

Upvotes: 5

Related Questions