Created
July 11, 2018 15:05
-
-
Save a-m-dev/8f8173ca244504ed197ee2e8201e354e 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
var SmoothScrolling = { | |
timer: null, | |
stop: function() { | |
clearTimeout(this.timer); | |
}, | |
scrollTo: function(id, callback) { | |
var settings = { | |
duration: 1000, | |
easing: { | |
outQuint: function(x, t, b, c, d) { | |
return c * ((t = t / d - 1) * t * t * t * t + 1) + b; | |
} | |
} | |
}; | |
var percentage; | |
var startTime; | |
var node = document.getElementById(id); | |
var nodeTop = node.offsetTop; | |
var nodeHeight = node.offsetHeight; | |
var body = document.body; | |
var html = document.documentElement; | |
var height = Math.max( | |
body.scrollHeight, | |
body.offsetHeight, | |
html.clientHeight, | |
html.scrollHeight, | |
html.offsetHeight | |
); | |
var windowHeight = window.innerHeight; | |
var offset = window.pageYOffset; | |
var delta = nodeTop - offset; | |
var bottomScrollableY = height - windowHeight; | |
var targetY = | |
bottomScrollableY < delta | |
? bottomScrollableY - (height - nodeTop - nodeHeight + offset) | |
: delta; | |
startTime = Date.now(); | |
percentage = 0; | |
if (this.timer) { | |
clearInterval(this.timer); | |
} | |
function step() { | |
var yScroll; | |
var elapsed = Date.now() - startTime; | |
if (elapsed > settings.duration) { | |
clearTimeout(this.timer); | |
} | |
percentage = elapsed / settings.duration; | |
if (percentage > 1) { | |
clearTimeout(this.timer); | |
if (callback) { | |
callback(); | |
} | |
} else { | |
yScroll = settings.easing.outQuint( | |
0, | |
elapsed, | |
offset, | |
targetY, | |
settings.duration | |
); | |
window.scrollTo(0, yScroll); | |
this.timer = setTimeout(step, 10); | |
} | |
} | |
this.timer = setTimeout(step, 10); | |
} | |
}; | |
export default SmoothScrolling; | |
/////////////////////////////////////////////////////////// HOT TO USE IT //////////////////////////////////////////// | |
// go to here : https://codesandbox.io/s/34n1jrw7lq |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
codeSandBox example : https://codesandbox.io/s/34n1jrw7lq