Created
February 10, 2017 17:50
-
-
Save aindong/18eff7b11a42fdbebe0c572ff4d94ff4 to your computer and use it in GitHub Desktop.
Smooth Scroll Utility Helper for ReactJs or JS applications
This file contains hidden or 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
export const smoothScroll = { | |
timer: null, | |
stop: function () { | |
clearTimeout(this.timer); | |
}, | |
scrollTo: function (id, callback) { | |
let settings = { | |
duration: 1000, | |
easing: { | |
outQuint: function (x, t, b, c, d) { | |
return c*((t=t/d-1)*t*t*t*t + 1) + b; | |
} | |
} | |
}; | |
let percentage; | |
let startTime; | |
let node = document.getElementById(id); | |
console.log(id); | |
let nodeTop = node.offsetTop; | |
let nodeHeight = node.offsetHeight; | |
let body = document.body; | |
let html = document.documentElement; | |
let height = Math.max( | |
body.scrollHeight, | |
body.offsetHeight, | |
html.clientHeight, | |
html.scrollHeight, | |
html.offsetHeight | |
); | |
let windowHeight = window.innerHeight | |
let offset = window.pageYOffset; | |
let delta = nodeTop - offset; | |
let bottomScrollableY = height - windowHeight; | |
let targetY = (bottomScrollableY < delta) ? | |
bottomScrollableY - (height - nodeTop - nodeHeight + offset): | |
delta; | |
startTime = Date.now(); | |
percentage = 0; | |
if (this.timer) { | |
clearInterval(this.timer); | |
} | |
let self = this; | |
function step () { | |
let yScroll; | |
let elapsed = Date.now() - startTime; | |
if (elapsed > settings.duration) { | |
clearTimeout(self.timer); | |
} | |
percentage = elapsed / settings.duration; | |
if (percentage > 1) { | |
clearTimeout(self.timer); | |
if (callback) { | |
callback(); | |
} | |
} else { | |
yScroll = settings.easing.outQuint(0, elapsed, offset, targetY, settings.duration); | |
window.scrollTo(0, yScroll); | |
self.timer = setTimeout(step, 10); | |
} | |
} | |
this.timer = setTimeout(step, 10); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment