Skip to content

Instantly share code, notes, and snippets.

@krishna19
Forked from joshbeckman/animatedScrollTo.js
Created September 22, 2018 06:00
Show Gist options
  • Select an option

  • Save krishna19/0e61a334e294e5c56d61995d5acb603f to your computer and use it in GitHub Desktop.

Select an option

Save krishna19/0e61a334e294e5c56d61995d5acb603f to your computer and use it in GitHub Desktop.

Revisions

  1. jbckmn created this gist Sep 30, 2013.
    31 changes: 31 additions & 0 deletions animatedScrollTo.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,31 @@
    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;
    };