What I\'m trying to do is make it so that if you click on a button, it scrolls down (smoothly) to a specific div on the page.
What I need is if you click on the butt
I played around with nico's answer a little and it felt jumpy. Did a bit of investigation and found window.requestAnimationFrame
which is a function that is called on each repaint cycle. This allows for a more clean-looking animation. Still trying to hone in on good default values for step size but for my example things look pretty good using this implementation.
var smoothScroll = function(elementId) {
var MIN_PIXELS_PER_STEP = 16;
var MAX_SCROLL_STEPS = 30;
var target = document.getElementById(elementId);
var scrollContainer = target;
do {
scrollContainer = scrollContainer.parentNode;
if (!scrollContainer) return;
scrollContainer.scrollTop += 1;
} while (scrollContainer.scrollTop == 0);
var targetY = 0;
do {
if (target == scrollContainer) break;
targetY += target.offsetTop;
} while (target = target.offsetParent);
var pixelsPerStep = Math.max(MIN_PIXELS_PER_STEP,
(targetY - scrollContainer.scrollTop) / MAX_SCROLL_STEPS);
var stepFunc = function() {
scrollContainer.scrollTop =
Math.min(targetY, pixelsPerStep + scrollContainer.scrollTop);
if (scrollContainer.scrollTop >= targetY) {
return;
}
window.requestAnimationFrame(stepFunc);
};
window.requestAnimationFrame(stepFunc);
}