How can I scroll to the top using vanilla JavaScript?
I'm trying to emulate scrollTop
(jQuery) in vanilla JS, so clicking it scrolls the element. This works great - if you haven't already scrolled the element. Therefore, it does not scroll the way back. Should my formula include window.pageYOffset
?
var moves = function(scrollz) {
var scrollPos = document.getElementById(scrollz).offsetTop - ((document.documentElement.clientHeight - document.getElementById(scrollz).offsetHeight) / 2);
var timerID = setInterval(function() {
window.scrollBy(0, speed);
if (window.pageYOffset >= scrollPos) {
clearInterval(timerID);
}
}, 13);
}
+3
source to share