Skip to content

Instantly share code, notes, and snippets.

@javiercastrodev
Forked from clemlatz/smooth-scroll.js
Created October 8, 2018 04:57
Show Gist options
  • Select an option

  • Save javiercastrodev/c90d5ba617d77c330c522cf7fdbccbf2 to your computer and use it in GitHub Desktop.

Select an option

Save javiercastrodev/c90d5ba617d77c330c522cf7fdbccbf2 to your computer and use it in GitHub Desktop.

Revisions

  1. @clemlatz clemlatz created this gist Sep 6, 2017.
    31 changes: 31 additions & 0 deletions smooth-scroll.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,31 @@
    /**
    * Smooth scroll animation
    * @param {int} endX: destination x coordinate
    * @param {int) endY: destination y coordinate
    * @param {int} duration: animation duration in ms
    */
    window.smoothScrollTo = function(endX, endY, duration) {
    var startX = window.scrollX || window.pageXOffset,
    startY = window.scrollY || window.pageYOffset,
    distanceX = endX - startX,
    distanceY = endY - startY,
    startTime = new Date().getTime();

    duration = typeof duration !== 'undefined' ? duration : 400;

    // Easing function
    var easeInOutQuart = function(time, from, distance, duration) {
    if ((time /= duration / 2) < 1) return distance / 2 * time * time * time * time + from;
    return -distance / 2 * ((time -= 2) * time * time * time - 2) + from;
    };

    var timer = window.setInterval(function() {
    var time = new Date().getTime() - startTime,
    newX = easeInOutQuart(time, startX, distanceX, duration),
    newY = easeInOutQuart(time, startY, distanceY, duration);
    if (time >= duration) {
    window.clearInterval(timer);
    }
    window.scrollTo(newX, newY);
    }, 1000 / 60); // 60 fps
    };