Created
January 19, 2019 14:51
-
-
Save ksk1015/71f8e4eeef351632f791525c611b9107 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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