I was looking for a good solution to scroll a div
(that is scrollable of course) to its top, with a single click, and in an animated way. I came across this (the #2 solution), which seemed pretty good, but it scrolls the whole window instead of a specific div
.
I slightly modified this function so that it can scroll a container instead of the whole window. Here's my version:
function scrollContainerToTop(scrollDuration, container_id) {
const container = document.getElementById(container_id),
scrollHeight = container.scrollTop,
scrollStep = Math.PI / (scrollDuration / 15),
cosParameter = scrollHeight / 2;
var scrollCount = 0,
scrollMargin,
scrollInterval = setInterval(function () {
if (container.scrollTop != 0) {
scrollCount = scrollCount + 1;
scrollMargin = cosParameter - cosParameter * Math.cos(scrollCount * scrollStep);
container.scrollTop = (scrollHeight - scrollMargin);
} else clearInterval(scrollInterval);
}, 15);
}
And here is a functional example, which you can try out: scroll the section with all the "Hello"s to the bottom, then click the button to scroll it up with javascript.
So my problem is that instead of just scrolling up, it scrolls up and down rapidly two or three times before settling on the top. However, if you call the scroller function with a bigger delay (say 300ms), then everything is fine. I tried it with Safari, Chrome, and an older version of Firefox as well, and every one of them produces the same glitchy result.
So why is this function glitchy if I supply it faster scroll times?