Skip to content

Instantly share code, notes, and snippets.

@YohannParis
Created August 16, 2016 20:50
Show Gist options
  • Save YohannParis/110a913c481c7d4b3b38026934f3730a to your computer and use it in GitHub Desktop.
Save YohannParis/110a913c481c7d4b3b38026934f3730a to your computer and use it in GitHub Desktop.
Easy way to smoothscroll to an element — http://jsfiddle.net/DruwJ/1/
window.smoothScrollTo = (function () {
var timer, start, factor;
return function (target, duration) {
var offset = window.pageYOffset,
delta = target - window.pageYOffset; // Y-offset difference
duration = duration || 1000; // default 1 sec animation
start = Date.now(); // get start time
factor = 0;
if( timer ) {
clearInterval(timer); // stop any running animations
}
function step() {
var y;
factor = (Date.now() - start) / duration; // get interpolation factor
if( factor >= 1 ) {
clearInterval(timer); // stop animation
factor = 1; // clip to max 1.0
}
y = factor * delta + offset;
window.scrollBy(0, y - window.pageYOffset);
}
timer = setInterval(step, 10);
return timer;
};
}());
// Example
smoothScrollTo(document.getElementById('bottom').offsetTop)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment