Skip to content

Instantly share code, notes, and snippets.

@hyamamoto
Created September 14, 2016 02:40
Show Gist options
  • Select an option

  • Save hyamamoto/392afde08805a666b8d08dfe7ae64459 to your computer and use it in GitHub Desktop.

Select an option

Save hyamamoto/392afde08805a666b8d08dfe7ae64459 to your computer and use it in GitHub Desktop.

Revisions

  1. hyamamoto created this gist Sep 14, 2016.
    70 changes: 70 additions & 0 deletions smooth-scroll.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,70 @@
    var scroll = {
    iterr: 30, // miliseconds
    tm: null,
    reset_timer: function () { // reset
    if (this.tm) {
    clearTimeout(this.tm);
    this.tm = null;
    }
    this.iterr = 30;
    },
    realtop_of: function (el) {
    var elm = el;
    var realTop = 0;
    do {
    realTop += elm.offsetTop;
    elm = elm.offsetParent;
    } while (elm);
    return realTop;
    },
    pagescroll: function () {
    var yOff = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop;
    return yOff;
    },
    go2top: function () {
    return scroll.go2elem(document.body);
    },
    go2id: function (id) {
    var targetEl = document.getElementById(id);
    return scroll.go2elem(targetEl);
    },
    go2elem: function (targetEl) {
    var eOff = targetEl.offsetTop;
    var tOff = this.realtop_of(targetEl.parentNode);
    return scroll.go2pos(eOff, tOff);
    },
    go2pos: function (eOff, tOff) {
    // scroll to tha element with the given id.
    // eOff : beginning point
    // tOff : terminus point
    this.reset_timer();
    var pOff, scrVal, pos, dir, step;

    pOff = this.pagescroll();
    if (pOff === null || isNaN(pOff) || pOff === 'undefined') pOff = 0;

    scrVal = eOff - pOff; // scroll amount

    if (scrVal > tOff) {
    pos = (eOff - tOff - pOff);
    dir = 1;
    }
    if (scrVal < tOff) {
    pos = (pOff + tOff) - eOff;
    dir = -1;
    }
    if (scrVal !== tOff) {
    step = ~~((pos / 4) + 1) * dir;
    this.iterr = (this.iterr > 1) ? this.iterr - 1: 0;

    window.scrollBy(0, step);

    this.tm = window.setTimeout(function () {
    scroll.go2pos(eOff, tOff);
    }, this.iterr);
    }
    if (scrVal === tOff) {
    this.reset_timer();
    }
    }
    };