Skip to content

Instantly share code, notes, and snippets.

@a-m-dev
Created July 11, 2018 15:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save a-m-dev/8f8173ca244504ed197ee2e8201e354e to your computer and use it in GitHub Desktop.
Save a-m-dev/8f8173ca244504ed197ee2e8201e354e to your computer and use it in GitHub Desktop.
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
@a-m-dev
Copy link
Author

a-m-dev commented Jul 11, 2018

codeSandBox example : https://codesandbox.io/s/34n1jrw7lq

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment