Skip to content

Instantly share code, notes, and snippets.

@kurtisdunn
Last active August 26, 2018 05:01
Show Gist options
  • Save kurtisdunn/4635054a60716dc95652c20b2cbdf552 to your computer and use it in GitHub Desktop.
Save kurtisdunn/4635054a60716dc95652c20b2cbdf552 to your computer and use it in GitHub Desktop.
Scroll To Function JS

Scroll To Top - Vanilla Javacript

function scrollTo(element, to, duration) {
if (duration < 0) return;
var difference = to - element.scrollTop;
var perTick = difference / duration * 2;
setTimeout(function() {
element.scrollTop = element.scrollTop + perTick;
scrollTo(element, to, duration - 2);
}, 10);
}
document.querySelector('.js-top-button').onclick = function () {
scrollTo(document.body, 0, 100);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment