I'm attempting to replicate the functionality of scrollTop
(using jQuery) using vanilla JS. When clicked, it should scroll to a specific element. While this works when the element is above the current scroll position, it does not function as intended if the element has already been scrolled past. Would incorporating window.pageYOffset
into my formula resolve this issue?
var scrollFunction = function(elementToScroll) {
var scrollPosition = document.getElementById(elementToScroll).offsetTop - ((document.documentElement.clientHeight - document.getElementById(elementToScroll).offsetHeight) / 2);
var timerID = setInterval(function() {
window.scrollBy(0, speed);
if (window.pageYOffset >= scrollPosition) {
clearInterval(timerID);
}
}, 13);
}