Skip to content

Instantly share code, notes, and snippets.

@joshbeckman
Created September 30, 2013 14:51
Show Gist options
  • Save joshbeckman/6764939 to your computer and use it in GitHub Desktop.
Save joshbeckman/6764939 to your computer and use it in GitHub Desktop.
ScrollTo animation using pure javascript and no jquery
document.getElementsByTagName('button')[0].onclick = function () {
scrollTo(document.body, 0, 1250);
}
function scrollTo(element, to, duration) {
var start = element.scrollTop,
change = to - start,
currentTime = 0,
increment = 20;
var animateScroll = function(){
currentTime += increment;
var val = Math.easeInOutQuad(currentTime, start, change, duration);
element.scrollTop = val;
if(currentTime < duration) {
setTimeout(animateScroll, increment);
}
};
animateScroll();
}
//t = current time
//b = start value
//c = change in value
//d = duration
Math.easeInOutQuad = function (t, b, c, d) {
t /= d/2;
if (t < 1) return c/2*t*t + b;
t--;
return -c/2 * (t*(t-2) - 1) + b;
};
@alexsad
Copy link

alexsad commented Jun 3, 2022

Hi, an alternative version with top and left props (typescript).

 
const scrollTo = ({element, top, left, duration}: {
        element: HTMLElement, 
        top: number,
        left: number, 
        duration: number,    
    }) => {
        const startTop = element.scrollTop;
        const startLeft = element.scrollLeft;
        const changeTop = top - startTop;
        const changeLeft = left - startLeft;
        const startDate = new Date().getTime();

        const animateScroll = function(){
            const currentDate = new Date().getTime();
            const currentTime = currentDate - startDate;            
            element.scrollTop = easeInOutQuad(currentTime, startTop, changeTop, duration);
            element.scrollLeft = easeInOutQuad(currentTime, startLeft, changeLeft, duration);

            if(currentTime < duration) {
                requestAnimationFrame(animateScroll);
            } else {
                element.scrollTop = top;
                element.scrollLeft = left;
            }
        };
        animateScroll();
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment