Reputation: 1037
I'm trying to imitate scrollTop
(jQuery) in vanilla JS, so on click it scrolls to an element. This works fine - unless you have already scrolled past the element. So it doesn't scroll the opposite way. Should my formula incorporate 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);
}
Upvotes: 3
Views: 22253
Reputation: 3949
scrollBy will scroll from "actual position" to "number of pixel defined" I think you might take a look at scrollTo
Upvotes: 4