Skip to content

Instantly share code, notes, and snippets.

@ksk1015
Created January 19, 2019 14:51
Show Gist options
  • Save ksk1015/71f8e4eeef351632f791525c611b9107 to your computer and use it in GitHub Desktop.
Save ksk1015/71f8e4eeef351632f791525c611b9107 to your computer and use it in GitHub Desktop.
function smoothScroll (scroller, endY) {
if (typeof scroller === 'number') {
endY = scroller;
scroller = window;
}
const startY = scroller === window ? scroller.pageYOffset : scroller.scrollTop;
const maxY = (scroller === window) ?
document.documentElement.scrollHeight - document.documentElement.clientHeight :
scroller.scrollHeight - scroller.clientHeight;
endY = Math.min(endY, maxY);
const dir = (endY - startY) / Math.abs(endY - startY);
const setY = scroller === window ? function (y) { scroller.scrollTo(0, y) } : function (y) { scroller.scrollTop = y }
let y = startY
const doScroll = function () {
const distance = Math.abs(endY - y);
if ( distance > 1.5 ) {
y += dir * Math.ceil(Math.min( distance / 3, 2000 ));
setY(y);
requestAnimationFrame(doScroll);
} else {
setY(endY);
}
}
requestAnimationFrame(doScroll);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment