JSFiddle - React, Tailwind, and code Playground
HTML
a
<br>a
<br>a
<br>a
<br>a
<br>a
<br>a
<br>a
<br>a
<br>a
<br>a
<br>a
<br>a
<br>a
<br>a
<br>a
<br>a
<br>a
<br>a
<br>a
<br>a
<br>a
<br>a
<br>a
<br>a
<br>a
<br>a
<br>a
<br>a
<br>a
<br>a
<br>a
<br>a
<br>a
<br>a
<br>a
<br>a
<br>a
<br>
JavaScript
// targetY: target Y coordinate to scroll to
// step: number of pixels to jump in each cycle when we are "far enough", so smaller number will result smoother but slower scroll
// intervalMs: the interval in milliseconds to execute each step
function smoothScrollTo(targetY, step, intervalMs) {
// get the current position, if the browser does not support "scrollTop", trz to use "pageYOffset"
var currentY = window.scrollTop || window.pageYOffset;
// if we have arrived, then stop and return
if (currentY == targetY) return;
// the signum of the difference, indicates which direction we should go
var sgn = Math.sign(targetY - currentY);
// the current distance between current and target y positions
var distance = Math.abs(currentY - targetY);
// calculate the step in pixels, slowing down if we are nearer
var step1 = (distance < 100) ? Math.max(step * distance / 50, 1) : step;
// execute the scroll
window.scrollTo(0, currentY + sgn * step1);
// call the next cycle
setTimeout(function () {
smoothScrollTo(targetY, step, intervalMs);
}, intervalMs);
}
smoothScrollTo(200, 10, 50);