Skip to content

Instantly share code, notes, and snippets.

@wireinet
Last active July 24, 2021 17:46
Show Gist options
  • Save wireinet/cb253d8e8f8a39c775fc9d0716ffcc54 to your computer and use it in GitHub Desktop.
Save wireinet/cb253d8e8f8a39c775fc9d0716ffcc54 to your computer and use it in GitHub Desktop.
<input id="top" type="button" value="Scroll down (1sec)" onclick="smoothScrollTo(document.getElementById('bottom').offsetTop)">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<input id="bottom" type="button" value="Scroll up (500ms)" onclick="smoothScrollTo(0, 500)">
<script>
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;
};
}());
</scrpt>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment