Created
August 16, 2016 20:50
-
-
Save YohannParis/110a913c481c7d4b3b38026934f3730a to your computer and use it in GitHub Desktop.
Easy way to smoothscroll to an element — http://jsfiddle.net/DruwJ/1/
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
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